PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 21, 2022

[FIXED] How do I execute model-related code only once in CakePhp 2.3

 April 21, 2022     cakephp, cakephp-2.3, php     No comments   

Issue

What I want:
I have a model Version with a member function update. I want this member function called once, every time a page is loaded.

What I did so far:
My current approach is to add the line

ClassRegistry::init('Version')->update();

into the beforeFilter() method of AppController

A previous solution was, to put the following code into app/Config/bootstrap.php:

App::uses('CakeEventManager', 'Event');
CakeEventManager::instance()->attach(
    function(){
        AppModel::getSingletonModel('Version')->update();
    },
    'Controller.startup'
);

(getSingletonModel does what it sounds like - get a singleton instance of the model)

The Problem:
Both solutions work, but if several controllers are loaded, the function is called several times. Which eats up resources.
Also, ClassRegistry has not been loaded, when bootstrap.php is executed. So I can't directly call the function there.

Additional Information:
The (technical) reason for several Controllers being called seems to be, that in a dashboard view some content is generated by calling $this->requestAction.

My Question:
Is there a way in CakePHP to call the function only once, like the file app/Config/bootstrap.php, but after the models are loaded?

Some Background: I'm developing a project in CakePHP 2.3 together with other developers.
I'm working on an autoupdate-system, where developers can add some code, which they want to run once (e.g. to adapt the database for added functionality).


Solution

Looks like I just asked the wrong question.

I made it work by loading ClassRegistry in the bootstrap.php

App::uses('ClassRegistry', 'Utility');
ClassRegistry::init('Version')->update();


Answered By - Till
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing