fuelphp 工作示例
在本章中,我們將學習如何在 fuelphp 中創(chuàng)建一個完整的基于 mvc 的 bookstore 應用程序。
步驟 1:創(chuàng)建項目
使用以下命令在 fuelphp 中創(chuàng)建一個名為"bookstore"的新項目。
oil create bookstore
第 2 步:創(chuàng)建布局
為我們的應用程序創(chuàng)建一個新布局。在位置fuel/app/views/layout.php 創(chuàng)建一個文件layout.php。代碼如下,
fuel/app/views/layout.php
<meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie = edge"> <meta name="viewport" content="width = device-width, initial-scale = 1"> <title><?php echo $title; ?></title> <!--bootstrap core css--> <link href="/assets/css/bootstrap.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script src="/assets/js/bootstrap.min.js"></script> <nav class="navbar navbar-inverse navbar-fixed-top"></nav><button type="button" class="navbar-toggle collapsed" datatoggle="collapse" data-target="#navbar" aria-expanded="false" ariacontrols="navbar"> toggle navigation </button> <a class="navbar-brand" href="#">fuelphp sample</a><ul class="nav navbar-nav"> <li class="active"><a href="/book/index">home</a></li> <li><a href="/book/add">add book</a></li> </ul><!--/.nav-collapse--><!--/.container-->echo $content;
在這里,我們使用引導程序模板。 fuelphp 對引導程序模板具有一流的支持。我們創(chuàng)建了兩個變量,title 和 content。 title 用于指定當前頁面的標題,content 用于指定當前頁面的詳細信息。
第 3 步:創(chuàng)建控制器
創(chuàng)建一個新控制器 controller_book 以顯示、添加、編輯和刪除書籍。創(chuàng)建一個新文件,fuel/app/classes/controller/book.php 并放置以下代碼。
fuel/app/classes/controller/book.php
class controller_book extends controller_template { public $template = 'layout'; public function action_index() { // create the view object $view = view::forge('book/index'); // set the template variables $this--->template->title = "book index page"; $this->template->content = $view; } }
這里,我們通過繼承模板控制器創(chuàng)建了書本控制器,并設置默認模板為fuel/app/views/layout.php。
步驟 4:創(chuàng)建索引視圖
創(chuàng)建一個文件夾,在fuel/app/views文件夾下的views目錄下預定。然后,在 book 文件夾中創(chuàng)建一個文件 index.php 并添加以下代碼,
fuel/app/views/index.php
<h3>index page</h3>
到目前為止,我們已經(jīng)創(chuàng)建了一個基本的書籍控制器。
第五步:修改默認路由
更新默認路由,將應用首頁設置為book控制器。打開默認路由配置文件fuel/app/config/routes.php,修改如下。
fuel/app/config/routes.php
return array ( '_root_' =--> 'book/index', // the default route '_404_' => 'welcome/404', // the main 404 route 'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'), );
現(xiàn)在,請求 url,http://localhost:8080/將返回圖書控制器的索引頁面,如下所示,
步驟 6:創(chuàng)建數(shù)據(jù)庫
在 mysql 服務器中新建一個數(shù)據(jù)庫,使用以下命令,
create database tutorialspoint_bookdb
然后,使用以下命令在數(shù)據(jù)庫中創(chuàng)建一個表,
create table book ( id int primary key auto_increment, title varchar(80) not null, author varchar(80) not null, price decimal(10, 2) not null );
使用以下 sql 語句向表中插入一些示例記錄。
insert into book(title, author, price) values( 'the c programming language', 'dennie ritchie', 25.00 ),( 'the c++ programming language', 'bjarne stroustrup', 80.00 ),( 'c primer plus (5th edition)', 'stephen prata', 45.00 ),('modern php', 'josh lockhart', 10.00),( 'learning php, mysql & javascript, 4th edition', 'robin nixon', 30.00 )
步驟 7:配置數(shù)據(jù)庫
使用位于fuel/app/config的數(shù)據(jù)庫配置文件db.php配置數(shù)據(jù)庫。
fuel/app/config/db.php
return array ( 'development' =--> array ( 'type' => 'mysqli', 'connection' => array ( 'hostname' => 'localhost', 'port' => '3306', 'database' => 'tutorialspoint_bookdb', 'username' => 'root', 'password' => 'password', 'persistent' => false, 'compress' => false, ), 'identifier' => '`', 'table_prefix' => '', 'charset' => 'utf8', 'enable_cache' => true, 'profiling' => false, 'readonly' => false, ), 'production' => array ( 'type' => 'mysqli', 'connection' => array ( 'hostname' => 'localhost', 'port' => '3306', 'database' => 'tutorialspoint_bookdb', 'username' => 'root', 'password' => 'password', 'persistent' => false, 'compress' => false, ), 'identifier' => '`', 'table_prefix' => '', 'charset' => 'utf8', 'enable_cache' => true, 'profiling' => false, 'readonly' => false, ), );
第 8 步:包含 orm 包
更新主配置文件以包含 orm 包。它位于"fuel/app/config/"。
fuel/app/config/config.php
'always_load' => array ( 'packages' => array ( 'orm' ), ),
第 9 步:創(chuàng)建模型
在位于"fuel/app/classes/model"的book.php中創(chuàng)建一個書本模型,定義如下:
fuel/app/classes/model/book.php
class model_book extends orm\model { protected static $_connection = 'production'; protected static $_table_name = 'book'; protected static $_primary_key = array('id'); protected static $_properties = array ( 'id', 'title' =--> array ( 'data_type' => 'varchar', 'label' => 'book title', 'validation' => array ( 'required', 'min_length' => array(3), 'max_length' => array(80) ), 'form' => array ( 'type' => 'text' ), ), 'author' => array ( 'data_type' => 'varchar', 'label' => 'book author', 'validation' => array ( 'required', ), 'form' => array ( 'type' => 'text' ), ), 'price' => array ( 'data_type' => 'decimal', 'label' => 'book price', 'validation' => array ( 'required', ), 'form' => array ( 'type' => 'text' ), ), ); protected static $_observers = array('orm\\observer_validation' => array ( 'events' => array('before_save') )); }
在這里,我們已將數(shù)據(jù)庫詳細信息指定為模型的屬性。它還包含驗證詳細信息。
第 10 步:展示圖書
更新書籍控制器中的索引操作以列出數(shù)據(jù)庫中的可用書籍。
fuel/app/classes/controller/book.php
class controller_book extends controller_template { public $template = 'layout'; public function action_index() { // create the view object $view = view::forge('book/index'); // fetch the book from database and set it to the view $books = model_book::find('all'); $view--->set('books', $books); // set the template variables $this->template->title = "book index page"; $this->template->content = $view; } }
在這里,我們使用 orm 從數(shù)據(jù)庫中獲取圖書詳細信息,然后將圖書詳細信息傳遞給視圖。
第 11 步:更新索引視圖
更新位于"fuel/app/views/book"的視圖文件index.php,完整的更新代碼如下,
fuel/app/views/book/index.php
<table class="table"> <thead> <tr> <th>#</th> <th>title</th> <th>author</th> <th>price</th> <th></th> </tr> </thead> <tbody> foreach($books as $book) { <tr> <td> echo $book['id']; </td> <td> echo $book['title']; </td> <td> echo $book['author']; </td> <td> echo $book['price']; </td> <td> <a href="/book/edit/<?php echo $book['id']; ?>">edit</a> <a href="/book/delete/<?php echo $book['id']; ?>">delete</a> </td> </tr> } </tbody> </table> <ul> </ul>
現(xiàn)在,請求 url,http://localhost:8080/將顯示如下頁面:
第 12 步:創(chuàng)建添加圖書的操作
創(chuàng)建將新書添加到書店的功能。在 book 控制器中創(chuàng)建一個新的 action,action_add 如下,
public function action_add() { // create a new fieldset and add book model $fieldset = fieldset::forge('book')->add_model('model_book'); // get form from fieldset $form = $fieldset->form(); // add submit button to the form $form->add('submit', '', array('type' => 'submit', 'value' => 'submit')); // build the form and set the current page as action $formhtml = $fieldset->build(uri::create('book/add')); $view = view::forge('book/add'); $view->set('form', $formhtml, false); if (input::param() != array()) { try { $book = model_book::forge(); $book->title = input::param('title'); $book->author = input::param('author'); $book->price = input::param('price'); $book->save(); response::redirect('book'); } catch (orm\validationfailed $e) { $view->set('errors', $e->getmessage(), false); } } $this->template->title = "book add page"; $this->template->content = $view; }
這里正在執(zhí)行以下兩個過程,
- 使用 fieldset 方法和 book 模型構建圖書表單以添加圖書。
- 處理圖書表單,當用戶輸入圖書信息并提交回表單時??梢酝ㄟ^檢查 input::param() 方法中任何提交的數(shù)據(jù)來找到它。處理表單涉及以下步驟-
- 收集圖書信息。
- 驗證圖書信息。我們已經(jīng)設置了在 save 方法之前調(diào)用的驗證。如果驗證失敗,則會拋出 orm\validationfailed 異常。
- 將圖書信息存儲到數(shù)據(jù)庫中。
- 成功后將用戶重定向到索引頁面。否則,再次顯示表單。
我們同時進行了兩種操作,即在同一操作中顯示表單以及處理表單。當用戶第一次調(diào)用該操作時,它會顯示該表單。當用戶輸入圖書信息并提交數(shù)據(jù)后,就會對表單進行處理。
第 13 步:為添加圖書操作創(chuàng)建視圖
為添加圖書操作創(chuàng)建視圖。新建一個文件fuel/app/views/book/add.php,輸入如下代碼,
<style> #form table { width: 90%; } #form table tr { width: 90% } #form table tr td { width: 50% } #form input[type = text], select { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } #form input[type = submit] { width: 100%; background-color: #3c3c3c; color: white; padding: 14px 20px; margin: 8px 0; border: none; border-radius: 4px; cursor: pointer; } #form div { border-radius: 5px; background-color: #f2f2f2; padding: 20px; } </style><h2>book form</h2> if(isset($errors)) { echo $errors; } echo $form;
這里,我們只是展示了在 action 方法中創(chuàng)建的表單。此外,我們還會顯示錯誤(如果有)。
第 14 步:檢查添加圖書操作
請求url,http://localhost:8080/book/add 或者點擊add book導航鏈接,會顯示如下表單,
表格
帶有數(shù)據(jù)的表單
輸入圖書信息并提交頁面后,圖書信息將被存儲到數(shù)據(jù)庫中,頁面被重定向到索引頁面,如下所示。
新增圖書的圖書列表
第 15 步:創(chuàng)建操作以編輯圖書
創(chuàng)建編輯和更新現(xiàn)有圖書信息的功能。在 book 控制器中創(chuàng)建一個新動作 action_edit,如下所示。
public function action_edit($id = false) { if(!($book = model_book::find($id))) { throw new httpnotfoundexception(); } // create a new fieldset and add book model $fieldset = fieldset::forge('book')->add_model('model_book'); $fieldset->populate($book); // get form from fieldset $form = $fieldset->form(); // add submit button to the form $form->add('submit', '', array('type' => 'submit', 'value' => 'submit')); // build the form and set the current page as action $formhtml = $fieldset->build(uri::create('book/edit/' . $id)); $view = view::forge('book/add'); $view->set('form', $formhtml, false); if (input::param() != array()) { try { $book->title = input::param('title'); $book->author = input::param('author'); $book->price = input::param('price'); $book->save(); response::redirect('book'); } catch (orm\validationfailed $e) { $view->set('errors', $e->getmessage(), false); } } $this->template->title = "book edit page"; $this->template->content = $view; }
它類似于添加操作,只是它在處理頁面之前通過 id 搜索請求的書。如果在數(shù)據(jù)庫中找到任何圖書信息,它將繼續(xù)并以表格形式顯示圖書信息。否則會拋出找不到文件的異常并退出。
第 16 步:為編輯操作創(chuàng)建視圖
為編輯圖書操作創(chuàng)建視圖。在這里,我們使用與添加操作相同的視圖。
第 17 步:檢查編輯書操作。
在圖書列表頁面點擊任意一本書的編輯鏈接,會顯示相應的圖書表單如下:
包含書籍詳細信息的表單
第 18 步:創(chuàng)建刪除圖書的操作
創(chuàng)建從書店刪除圖書的功能。在 book 控制器中創(chuàng)建一個新的 action,action_delete,如下所示,
public function action_delete($id = null) { if ( ! ($book = model_book::find($id))) { throw new httpnotfoundexception(); } else { $book->delete(); } response::redirect('book'); }
在這里,我們使用提供的圖書 id 檢查數(shù)據(jù)庫中圖書的存在。如果找到該書,則將其刪除并重定向到索引頁。否則會顯示頁面未找到信息。
第 19 步:檢查刪除操作
點擊圖書列表頁面中的刪除鏈接,檢查刪除操作。它將刪除請求的圖書,然后再次重定向到索引頁。
最后,添加、編輯、刪除和列出圖書信息的所有功能都已創(chuàng)建。
與其他基于 mvc 的 php 框架相比,fuelphp 簡單、靈活、可擴展且易于配置。它提供了現(xiàn)代 mvc 框架的所有功能。它可以按原樣使用,也可以完全更改以滿足我們的需要。最重要的是,它是 web 開發(fā)的絕佳選擇。