Optimization in blocks controllers

Permalink
I am a bit surprised by how often a blocks controller is instantiated/loaded when concrete5 loads a page with a block on:

- Controller is loaded four times before the chosen action is run in controller
- After action has run, the controller is again loaded eight times before the event on_start is run and view is processed.

Another way to illustrate the workflow:
constructor in controller runs
constructor in controller runs
constructor in controller runs
constructor in controller runs
action in controller runs
constructor in controller runs
constructor in controller runs
constructor in controller runs
constructor in controller runs
constructor in controller runs
constructor in controller runs
constructor in controller runs
constructor in controller runs
on_start in controller runs
view is processed

In the controller I instantiate a heavy model. The model contains some functionality that the view also needs, so I pass the model on from controller to view with the command $this->set('model', $model);

The problem is that the model must be loaded before the action is run, because almost all the actions need this model.

My temporary solution is to have a protected function init() with the model instantiation which all the action functions load.

Where can I put model instantiation so that it only loads once and that it loads before the action?

itrio
 
RadiantWeb replied on at Permalink Reply
RadiantWeb
on_start(){} in the controller I think is what you want.

but the "standard" way to take advantage of model functions would be to define the model as such:

Loader::model('my_model','my_package');


then call the function from the class name, in this case the someClass function of the MyModel class within the my_model.php model file:

$model_function = MyModel::someClass();


Chad
itrio replied on at Permalink Reply
itrio
The problem with event on_start() is that it does not run in the same instance of the controller as the action and that it runs AFTER the actions (my model variable $this->model is then null).

If this is obviously wrong, then please tell me.

I can't find any good documentation about events in block controllers anywhere. Maybe I have misunderstood something?
ScottC replied on at Permalink Reply
ScottC
few things:

if you are using your model to access the db, then I would this->set('modelVar',$model->getModelVar());

You can use cache, set the object's name and append the bID(Cache::set($beefyControllerName.$this->bID,$this->model->excrutiatinglyLongProcess($bID));

You can also call another method in a block's onstart via that controller action if you want, function actionName(){
$this->expensiveData($this->model->expensiveData());
parent::on_start();
}

I still don't quite understand it though, so I could be entirely off base here :)

-Scott