Home > Article > Backend Development > CodeIgniter study notes 3: Extending CI controllers and models, codeigniterci_PHP tutorial
Sometimes it is necessary to perform unified operations on the controllers in CI, such as login and permission verification. This can be achieved by extending the CI controller.
To extend the CI controller, you only need to create a MY_Controller class inherited from the CI_Controller class in the application/core folder, and then implement the logic you need in this class.
Regarding the above sentence, there are two points that need to be explained:
1. Why is it in the application/core folder: Because the base class CI_Controller is in the system/core folder, and it needs to correspond to the system.
2. Why is the prefix of the extended controller MY_? Can it be changed to another one? This prefix is defined in application/config/config.php:
<span>$config</span>['subclass_prefix'] = 'MY_';
Just need to match these two places.
Example application/models/user_model.php:
<?<span>php </span><span>/*</span><span>* * User_model </span><span>*/</span> <span>class</span> User_model <span>extends</span><span> CI_Model{ </span><span>//</span><span>return all users</span> <span>public</span> <span>function</span><span> getAll() { </span><span>$res</span> = <span>$this</span> -> db -> get('test'<span>); </span><span>return</span> <span>$res</span> -><span> result(); } }</span>
Note:
1. The file name is all lowercase
2. Capitalize the first letter of the class name
3. The attributes in the super object can be used in the model
4. It is recommended to use _model as the suffix to prevent conflicts with other class names
Usage example:
<span>public</span> <span>function</span><span> index() { </span><span>//</span><span>load model</span> <span>$this</span> -> load -> model('User_model'<span>); </span><span>$usermodel</span> = <span>$this</span> -> User_model -><span> getAll(); </span><span>//</span><span>别名</span> <span>$this</span> -> load -> model('User_model', 'user'<span>); </span><span>$usermodel</span> = <span>$this</span> -> user -><span> getAll(); </span><span>var_dump</span>(<span>$usermodel</span><span>); }</span>
The model is mainly used to standardize the project structure.