CodeIgnter controllers

controller是CodeIgnter的核心

  1. example.com/index.php/blog/  

在上例中,CodeIgniter 會嘗試在找一個 blog.php 的控制器,並且找到後載入進來。

建立一個blog.php的檔案,然後在controller寫這段

  1. <?php   
  2. class Blog extends CI_Controller {   
  3.   
  4.     public function index()   
  5.     {   
  6.         echo 'Hello World!';   
  7.     }   
  8. }   
  9. ?>  

這樣在example.com/index.php/blog/,就會看到"Hello World!",記得class的命名要用大寫

在後面在寫一個function
  1. <?php   
  2. class Blog extends CI_Controller {   
  3.   
  4.     public function index()   
  5.     {   
  6.         echo 'Hello World!';   
  7.     }   
  8.   
  9.     public function comments()   
  10.     {   
  11.         echo 'Look at this!';   
  12.     }   
  13. }   
  14. ?>  

這樣就可以在example.com/index.php/blog/comments/看到'Look at this!'

也可以在網址帶參數,例如: example.com/index.php/products/shoes/sandals/123
  1. <?php   
  2. class Products extends CI_Controller {   
  3.   
  4.     public function shoes($sandals$id)   
  5.     {   
  6.         echo $sandals;   
  7.         echo $id;   
  8.     }   
  9. }   
  10. ?>   

CodeIgniter 控制器(Controllers)

留言