[PHP]架構教程:CodeIgniter架構的簡易使用

來源:互聯網
上載者:User

CodeIgniter是一個小巧但功能強大的 PHP 架構,官網地址。

在官網可以下載該架構。


下面來說明一下CodeIgniter中的簡單操作。

一、Controller的建立與設定

1.在Controller目錄下建立blog.php檔案:

2.blog.php中的代碼如下:

<?phpclass Blog extends CI_Controller {function index(){echo 'Hello World!';}}?>

3.輸入地址。注意:不要加尾碼。瀏覽頁面:

這裡顯示的其實是index函數中的資料,因為預設會調用index方法。

我們不妨將代碼做如下修改:

<?phpclass Blog extends CI_Controller {function index(){echo 'Hello World!';}function hello(){echo 'Hello WHY!';}}?>

然後將訪問路徑也修改一下,就會發現其實輸入或者不輸入/index都是訪問的index方法,但是如果輸入其他值就會訪問其他的function的內容:


在CodeIgniter中,很多設定都已經配置好了,我們可以直接修改。

比如修改預設的訪問頁面,在applications/config中有一個route.php:

$route['default_controller'] = "welcome";$route['404_override'] = '';

將其中的default_controller改成blog,再在工作列中輸入index.php就會發現輸出的是HelloWorld,也就是訪問了blog.php頁面:

二、View的建立與設定

1.在views目錄下建立檔案blog_view.php:

2.返回到controller檔案夾下的blog.php,將簡單的echo改為載入blog_view頁面,實現其controller的真正價值:

<?phpclass Blog extends CI_Controller {function index(){$this->load->view('blog_view');}}?>

3.在頁面中輸入網址進行訪問,發現頁面已經發生了變化:

三、Controller與View之間的資料轉送

1.將Controller中的代碼作如下修改:

<?phpclass Blog extends CI_Controller {function index(){$data['myName']="WHY";$data['head']="'s Blog !";$this->load->view('blog_view',$data);}}?>

2.將View中的代碼作如下修改,注意,不是使用data數組,而是直接的$調用資料:

<html><head><title><?php echo $myName.$head?></title></head><body><h1>I am <?php echo $myName ?></h1></body></html>

3.瀏覽網站:


PS:在CodeIgniter 中<?php echo $myName ?>等價於<?=$myName ?>


下面來使用php輸出一個數組。

1.在Controller中作如下修改添加一個數組:

<?phpclass Blog extends CI_Controller {function index(){$data['myName']="WHY";$data['head']="'s Blog !";$data['todo']=array('eat','sleep','call');$this->load->view('blog_view',$data);}}?>

2.在View中作如下修改顯示數組:

<html><head><title><?php echo $myName.$head?></title></head><body><h1>I am <?php echo $myName ?></h1><ol><?php foreach($todo as $item): ?><li><?=$item?></li><?php endforeach; ?></ol></body></html>

3.重新整理頁面,已經可以正常顯示了:

如果不習慣endforeach,也可以使用標準的PHP語言:

<html><head><title><?php echo $myName.$head?></title></head><body><h1>I am <?php echo $myName ?></h1><ol><?php foreach($todo as $item){ ?><li><?= $item?></li><?php } ?></ol></body></html>

當然,也可以重寫構造方法:

<?phpclass Blog extends CI_Controller {function __construct(){parent::__construct(); }function index(){$data['myName']="WHY";$data['head']="'s Blog !";$data['todo']=array('eat','sleep','call');$this->load->view('blog_view',$data);}}?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.