D
D
Dmitry Petrik2014-10-23 06:23:55
Yii
Dmitry Petrik, 2014-10-23 06:23:55

Yii. How to use your functions in the controller?

How to write your own functions in the controller so that they can be called from any action?
In principle, I found a solution, but something tells me that it smells of bydlokoding :)
I do it this way. My function inside controller:

public static function myFunction(){
//тело функции
}

You can call it later from any action like this:
MyController::myFunction();
To what extent is this decision correct? And what is the best way to do it?
PS Yii first version

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Cyril, 2014-10-23
@Flexo

Something prompts to me that it is better (more correctly) to implement the methods in MODEL. This will not conflict with MVC. And already from the controller to call the methods of the model.
It can also be moved to a component.

R
Rustamka Vorontsov, 2014-10-23
@rmfordev

It's better to use a model to store your functions.
And controllers should be thin.
For example, to get a user by the id of the User model, you can implement it statically:

<?php
class User extends CActiveRecord {
...
static function get($id){
        return self::model()->findByPk($id);
}
...

It will be possible to call as
Just do not confuse static with public

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question