Increasing performance in controllers

public function initialize()
{
    $user = Users::findFirstById($id);
    $this->user = $user;
}

Is this increasing performance when using $this->user in other actions, or is there more elegant way to not repeat $user = Users::findFirstById($id); in every action ????

You are asking a very good question.

It depends on what your trying to accomplish with the data. if you are logging a user into your app, for example, you could use Sessions. You would find that user using the above method, upon login attempt. Upon successful login, you would fire up a session and store selected user details in that session. These details would then be avalible through the session object, which would free your app from having to make constant queries.

I cannot get into some examples, but I would suggest reading through a few bits for more info and ideas to get you started:

Hello,

If all methods in your controller must find this record, i think it's a great idea, it's really readable and more DRY. But you speak about increasing performance, imagine you get a simple method like "superman()" who doesn't use this record, it's useless to find this record ... Anyway, Phalconphp is really fast !

Also you need to ask yourself this question, "Will you need that information in every method of that class?".



15.8k
edited Apr '14

Sorry, here is example:

class someController extends ControllerBase
{
    public function initialize()
    {
        $user = Users::findFirstById($id);

        $this->user = $user;


        // do something on $user
        $user->someRelations; //etc
    }

    public function editAction()
    {
        $this->user->someOtherRelations; //etc
    }
}

I need allways do some operations on Users and related tables in initialize(), and other operations on Users and related tables in some Actions.

Is it better way/performance than (creating $user) $user = Users::findFirstById($id); in editAction() (omitting DRY)??



7.2k

You probably forgot : PHP is born to die.

On every request your apllication is start on zero.

If you are sure that the data has not changed, you can use Cookie or Session or localStorage.



15.8k
edited Apr '14

but I mean - initialize() and editAction() in same request. Btw I think storing this data in sessions is not possible when using relations.



7.2k

Of course, initialize() and editAction() in same request. You can try onConstruct() action also. First calling initialize(), when object is construicted - onConstruct()

Putting that logic in initialize() as opposed to every action will not increase performance. The code will need to be run once regardless, so you're not saving any cycles.

What you are saving is having duplicate code in each separate action. If you've determined you need access to the current user for every action, then initialize() is the best place to put that logic.