Home > Article > Backend Development > CodeIgniter study notes 3: Extending CI controllers and models
1. Expand the controller in CI
Sometimes it is necessary to perform unified operations on the controller 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_';
You only need to match these two places.
2. Model
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. The first letter of the class name is capitalized
3. You can use super in the model Attributes in objects
4. It is recommended to use _model as a suffix to prevent conflicts with other class names
Usage examples:
<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>
Models are mainly used to standardize the project structure.
The above introduces the CodeIgniter study note three: expanding the controller and model of CI, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.