|
| 1 | +************************ |
| 2 | +Extending the Controller |
| 3 | +************************ |
| 4 | + |
| 5 | +CodeIgniter's core Controller should not be changed, but a default class extension is provided for you at |
| 6 | +**app/Controllers/BaseController.php**. Any new controllers you make should extend ``BaseController`` to take |
| 7 | +advantage of preloaded components and any additional functionality you provide:: |
| 8 | + |
| 9 | + <?php namespace App\Controllers; |
| 10 | + |
| 11 | + use CodeIgniter\Controller; |
| 12 | + |
| 13 | + class Home extends BaseController { |
| 14 | + |
| 15 | + } |
| 16 | + |
| 17 | +Preloading Components |
| 18 | +===================== |
| 19 | + |
| 20 | +The base controller is a great place to load any helpers, models, libraries, services, etc. that you intend to |
| 21 | +use every time your project runs. Helpers should be added to the pre-defined ``$helpers`` array. For example, if |
| 22 | +you want the HTML and Text helpers universally available:: |
| 23 | + |
| 24 | + protected $helpers = ['html', 'text']; |
| 25 | + |
| 26 | +Any other components to load or data to process should be added to the constructor ``initController()``. For |
| 27 | +example, if your project uses the Session Library heavily you may want to initiate it here:: |
| 28 | + |
| 29 | + public function initController(...) |
| 30 | + { |
| 31 | + // Do Not Edit This Line |
| 32 | + parent::initController($request, $response, $logger); |
| 33 | + |
| 34 | + $this->session = \Config\Services::session(); |
| 35 | + } |
| 36 | + |
| 37 | +Additional Methods |
| 38 | +================== |
| 39 | + |
| 40 | +The base controller is not routable (system config routes it to 404 Page Not Found). As an added security |
| 41 | +measure **all** new methods you create should be declared as ``protected`` or ``private`` and only be accessed through the |
| 42 | +controllers you create that extend ``BaseController``. |
| 43 | + |
| 44 | +Other Options |
| 45 | +============= |
| 46 | + |
| 47 | +You may find that you need more than one base controller. You can create new base controllers as long as any other controllers that you make extend the correct base. For example, if your project |
| 48 | +has an involved public interface and a simple administrative portal you may want to extend ``BaseController`` to |
| 49 | +the public controllers and make ``AdminController`` for any administrative controllers. |
| 50 | + |
| 51 | +If you do not want to use the base controller you may bypass it by having your controllers extend the system |
| 52 | +Controller instead:: |
| 53 | + |
| 54 | + class Home extends Controller |
| 55 | + { |
| 56 | + |
| 57 | + } |
0 commit comments