yii framework - design pattern and database and form (1)

32 1.3K 11
yii framework - design pattern and database and form (1)

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Yii Framework Version 1.0 (Team JustLook) JustLook Yii Framework Trang 2/31 Introduction Yii PHP framework hỗ trợ tốt cho việc phát triển Web 2.0 Yii giúp nhà phát triển xây dựng ứng dụng phức tạp với thời gian nhanh Yii phát âm Yee [ji:], Yii viết tắt “Yes It Is!” Ý nghĩa “Is it fast? Is it secure? Is it professional? Is it right for my next project? Yes, it is!” Yii hoàn toàn miễn phí, ứng dụng Web mã nguồn mở phát triển ngôn ngữ PHP5 Yii giúp cho việc phát triển ứng dụng Web tuân theo khuôn khổ nhằm đảm bảo tính hiệu quả, tính mở rộng, tính bảo trì sản phẩm Tối ưu hiệu suất, Yii lựa chọn hoàn hảo cho dự án có quy mơ Yii cho phép nhà phát triển kiểm sốt tồn cấu hình Yii cung cấp cơng cụ giúp kiểm tra sửa lỗi ứng dụng dễ dàng Lịch sử Yii sáng lập Qiang Xue, người trước phát triển bảo trì Prado framework Dự án Yii ngày 01/01/2008 sau gần năm phát triển, ngày 03/12/2008 Yii 1.0 thức phát hành Ý tưởng Yii kết hợp nhiều ý tưởng từ framework ứng dựng Web tiếng khác Dưới số ý tưởng Yii tham khảo: • Prado: nguồn gốc chủ yếu cho ý tưởng phát triển Yii, bao gồm: component mơ hình lập trình hướng kiện, lớp database, mơ hình kiến trúc ứng dụng, i18n l10n, nhiều tính khác • Ruby on Rails: Yii kế thừa quy ước cấu hình • jQuery: tích hợp Yii framework • Symfony: Yii kế thừa ý tưởng filter kiến trúc plug-in • Joomla: Yii kế thừa cách thiết kế module message translation JustLook Yii Framework Contents Trang 3/31 JustLook Yii Framework Trang 4/31 Overview MVC Controller Model View MVC MVC mơ hình kiến trúc phần mềm sử dụng phổ biến phát triển ứng dụng Web Mục đích MVC là: • Tách riêng thành phần logic với giao diện người dùng • Giúp cho việc thay đổi thành phần dễ dàng mà không làm ảnh hưởng đến thành phần khác • Dễ dàng phát triển bảo trì ứng dụng Model Là thể cấu trúc liệu Model sử dụng để lưu trữ liệu quy tắc business liên quan Model đại diện cho đối tượng liệu Nó row database table form input người dùng Mỗi trường (field) object thuộc tính (attribute) model JustLook Yii Framework Trang 5/31 View View chủ yếu yếu tố giao diện người dùng Chịu trách nhiệm trình bày thể model dạng mà người dùng mong muốn Nó chứa câu lệnh (PHP, ASP, …) với mục đích trình bày Controller Cơng việc chủ yếu controller điều kiển, xử lý request người dùng Liên kết model với view Kiểm soát response JustLook Yii Framework Trang 6/31 Best MVC Practices Một mơ hình MVC tốt cần phải thực nguyên tắc sau: Model • Nên o Chứa thuộc tính đại diện cho liệu cụ thể o Chứa business logic nhằm đảm bảo liệu đáp ứng yêu cầu thiết kế o Có thể chứa mã thao tác với database • Tránh o Sử dụng $_GET, $_POST biến trực tiếp gắn liến với request người dùng o Nhúng mã HTML mã trình diễn khác (echo, …) View • Nên o Chứa mã trình diễn, HTML, PHP, ASP,… đơn giản để thể hiện, định dạng liệu o Có thể truy cập thuộc tính (property) phương thức (method) controller model với mục đích trình bày • Tránh o Chứa mã truy vấn liệu JustLook Yii Framework Trang 7/31 o Truy cập trực tiếp đến $_GET, $_POST, biến tương tự khác đại diện cho request người dùng Controller • Nên o Có thể truy cập $_GET, $_POST biến tương tự khác đại diện cho request người dùng o Có thể tạo thực thể (instance) model • Tránh o Chứa câu lệnh truy vấn SQL o Chứa mã HTML ngôn ngữ trình diễn khác JustLook Yii Framework Trang 8/31 CakePHP vs Yii Model Model View View Widget Widget Controller Controller Index.php Index.php CakePHP Framework Application Application App components App components Yii Framework CakePHP đánh giá framework có mơ hình MVC chuẩn nhất, Các thành phần CakePHP hồn tồn tương ứng với mơ hình MVC Yii sử dụng mơ hình MVC thiết kế Ngồi thành phần bản, Yii bổ sung thêm số thành phần (Application, App Components, Widget, …) Các thành phần team giới thiệu chi tiết phần sau Ghi chú: tài liệu chủ yếu giới thiệu Yii, cty Green Global mạnh mảng CakePHP framework Vì trình giới thiệu Yii, team JustLook đưa khác CakePHP Yii Để người so sánh, biết khác biệt CakePHP Yii JustLook Yii Framework Trang 9/31 Yii Basic Workflow Về bản, cách làm việc Yii thực qua bước sau: Yêu cầu (request) người dùng trình duyệt gửi cho Web server Web server chuyển tiếp request cho index.php xử lý Index.php có chức tạo thực thể Application thực thi Application tạo App Component (App Component thành phần ứng dụng, vd: UrlManager, HttpRequest) App Component gửi thành phần cho Application quản lý Application xác định controller action từ request gửi chúng cho UrlManager quản lý Tiếp đến Application tiến hành thực thi controller Controller tạo model để xử lý liệu Model gửi liệu cho Controller Controller gửi biến, thể model cho View View tạo Widget View thực trình bày trang web JustLook Yii Framework Trang 10/31 Đôi cần thay đổi workflow để tùy biến trang web Yii cho phép làm điều qua workflow sau: App components JustLook Yii Framework Trang 18/31 Validator bí danh xác định trước Yii (như ví dụ trên, sử dụng bí danh required) b) Relational Active Record Phần giới thiệu chi tiết phần Active Record (Working with Database) c) Một vài phương thức liên quan đến truy vấn CSDL • Protected Methods o beforeSave() / afterSave() o beforeDelete() / afterDelete() o beforeValidate() / afterValidate() o beforeFind() / afterFind() • Events o onBeforeSave / onAfterSave o onBeforeDelete / onAfterDelete o onBeforeValidate / onAfterValidate o onBeforeFind / onAfterFind View View PHP script bao gồm chủ yếu yếu tố giao diện người dùng Nó chứa câu lệnh PHP đơn giản với mục đích trình bày Làm việc với view cần ý đến phương thức sau: • Public methods o render(): Renders a view with a layout o renderDynamic(): Renders dynamic content returned by the specified callback o renderDynamicInternal(): This method is internally used o renderFile() or renderInternal(): Renders a view file o renderPartial(): Renders a view o renderText(): Renders a static text string • Protected methods o beforeRender() / afterRender() Widget Widget thành phần chủ yếu cho mục đích trình bày Nó tạo giao diện người dùng phức tạp khép kín JustLook Yii Framework Trang 19/31 Working with Database Data Access Objects (DAO) Query Builder Active Record Data Access Objects (DAO) DAO cung cấp API chung để truy cập liệu lưu trữ hệ thống quản lý CSDL khác Yii DAO chủ yếu bao gồm lớp (class) sau: • CDbConnection: đại diện cho kết nối đến CSDL • CDbCommand: đại diện cho câu lệnh truy vấn SQL để thực CSDL • CDbDataReader: đại diện cho tập hợp hàng (row) từ kết câu truy vấn • CdbTransaction: đại diện cho giao dịch (transaction) với DB Establishing Database Connection (Thiết lập kết nối CSDL) Để thiết lập kết nối với CSDL ta tạo đối tượng CdbConnection với cấu trúc sau: $connection=new CDbConnection($dsn,$username,$password); // establish connection You may try catch possible exceptions $connection->active=true; $connection->active=false; // close connection $dsn tùy thuộc vào trình điều khiển CSDL PDO sử dụng Dưới danh sách DSN thường sử dụng: • • • • • SQLite: sqlite:/path/to/dbfile MySQL: mysql:host=localhost;dbname=testdb PostgreSQL: pgsql:host=localhost;port=5432;dbname=testdb SQL Server: mssql:host=localhost;dbname=testdb Oracle: oci:dbname=//localhost:1521/testdb $username $password thông tin để kết nối đến CSDL Ta thiết lập kết nối CSDL file config (protected/config/main.php) sau: JustLook Yii Framework Trang 20/31 array( 'components'=>array( 'db'=>array( 'class'=>'CDbConnection', 'connectionString'=>'mysql:host=localhost;dbname=testdb', 'username'=>'root', 'password'=>'password', 'emulatePrepare'=>true, // needed by some MySQL installations ), ), ) Với cách cấu trên, để truy cập đến DB connection ta sử dụng Yii::app()->db Executing SQL Statements (Thực thi câu lệnh truy vấn SQL) Khi kết nối CSDL thiết lập, câu lệnh truy SQL thực cách sử dụng CDbCommand Để tạo CDbCommand ta sử dụng phương thức CDbConnection::createCommand() Xem ví dụ: $rowCount=$command->execute(); $dataReader=$command->query(); $rows=$command->queryAll(); $row=$command->queryRow(); $column=$command->queryColumn(); $value=$command->queryScalar(); row // // // // // // execute the non-query SQL execute a query SQL query and return all rows of result query and return the first row of result query and return the first column of result query and return the first field in the first Một câu lệnh SQL thực thi thông qua CDbCommand cách sau: • execute(): thực non-query SQL, INSERT, UPDATE DELETE • query(): thực câu truy vấn trả tập hợp hàng (row) liệu, SELECT Fetching Query Results (Lấy kết truy vấn) Để lấy kết truy vấn ta sử dụng CdbDataReader->read() $dataReader=$command->query(); // calling read() repeatedly until it returns false while(($row=$dataReader->read())!==false) { } JustLook Yii Framework Trang 21/31 // using foreach to traverse through every row of data foreach($dataReader as $row) { } // retrieving all rows at once in a single array $rows=$dataReader->readAll(); Using Transactions (Sử dụng transaction) Để sử dụng transaction (giao dịch) ta sử dụng cấu trúc sau: $transaction=$connection->beginTransaction(); try { $connection->createCommand($sql1)->execute(); $connection->createCommand($sql2)->execute(); // other SQL executions $transaction->commit(); } catch(Exception $e) // an exception is raised if a query fails { $transaction->rollBack(); } Binding Parameters Để tránh công SQL Injection cải thiện hiệu suất câu lệnh truy vấn SQL ta sử dụng tham số ràng buộc (binding parameters) Xem ví dụ sau: // an SQL with two placeholders ":username" and ":email" $sql="INSERT INTO tbl_user (username, email) VALUES(:username,:email)"; $command=$connection->createCommand($sql); // replace the placeholder ":username" with the actual username value $command->bindParam(":username",$username,PDO::PARAM_STR); // replace the placeholder ":email" with the actual email value $command->bindParam(":email",$email,PDO::PARAM_STR); $command->execute(); // insert another row with a new set of parameters $command->bindParam(":username",$username2,PDO::PARAM_STR); $command->bindParam(":email",$email2,PDO::PARAM_STR); $command->execute() Để biết chi tiết tham số ràng buộc, vui lòng xem thêm link http://www.php.net/manual/en/pdostatement.bindparam.php JustLook Yii Framework Trang 22/31 Query Builder Yii Query Builder cung cấp việc viết câu lệnh SQL theo hướng đối tượng Nó cho phép sử dụng phương thức thuộc tính để chia nhỏ câu lệnh SQL thành phần đơn giản Các phần sau Yii kết hợp lại thực thi thông qua DAO Dưới cách sử dụng điển hình Query Builder để xây dựng câu lệnh SQL SELECT $user = Yii::app()->db->createCommand() ->select('id, username, profile') ->from('tbl_user u') ->join('tbl_profile p', 'u.id=p.user_id') ->where('id=:id', array(':id'=>$id)) ->queryRow(); Việc sử dụng Query Builder có lợi ích sau: • Cho phép xây dựng câu lệnh truy vấn phức tạp (nhưng dễ viết hơn) • Tự động bọc (quote) tên table cách thêm ký tự (`) vào tên table nhằm tránh xung đột với từ khóa SQL ký tự đặc biệt • Tự động bọc giá trị tham số sử dụng tham số ràng buộc (parameter binding) có thể, giảm nguy bị cơng SQL Injection • Đơn giản hóa việc chuyển đổi sang tảng DB khác Trước sử dụng Query Builder, ta kết nối đến CSDL cách sử dụng CDbCommand DAO $command = Yii::app()->db->createCommand(); Building Data Retrieval Queries Các phương thức liên quan đến việc truy vấn CSDL: • select(): specifies the SELECT part of the query • selectDistinct(): specifies the SELECT part of the query and turns on the DISTINCT flag • from(): specifies the FROM part of the query • where(): specifies the WHERE part of the query • join(): appends an inner join query fragment • group(): specifies the GROUP BY part of the query • having(): specifies the HAVING part of the query • order(): specifies the ORDER BY part of the query JustLook Yii Framework Trang 23/31 • limit(): specifies the LIMIT part of the query • offset(): specifies the OFFSET part of the query • union(): appends a UNION query fragment $users = Yii::app()->db->createCommand() ->select('*') ->from('tbl_user') ->queryAll(); $user = Yii::app()->db->createCommand() ->select('id, username, profile') ->from('tbl_user u') ->join('tbl_profile p', 'u.id=p.user_id') ->where('id=:id', array(':id'=>$id)) ->queryRow(); Building Data Manipulation Queries Để sử dụng thao tác thêm, sửa, xóa liệu Yii Query Builder cung cấp phương thức sau: • insert(): thêm hàng (row) vào bảng (table) • update(): bảng • delete(): xóa liệu từ bảng Xem ví dụ sau: // build and execute the following SQL: // INSERT INTO `tbl_user` (`name`, `email`) VALUES (:name, :email) $command->insert('tbl_user', array( 'name'=>'Tester', 'email'=>'tester@example.com', )); // build and execute the following SQL: // UPDATE `tbl_user` SET `name`=:name WHERE id=:id $command->update('tbl_user', array( 'name'=>'Tester', ), 'id=:id', array(':id'=>1)); // build and execute the following SQL: // DELETE FROM `tbl_user` WHERE id=:id $command->delete('tbl_user', 'id=:id', array(':id'=>1)); JustLook Yii Framework Trang 24/31 Building Schema Manipulation Queries Để thao tác lượt đồ CSDL ta sử dụng phương thức sau: • • • • • • • • • • createTable(): tạo bảng (table) renameTable(): đổi tên bảng dropTable(): xóa bảng truncateTable(): truncates bảng addColumn(): thêm cột (column) cho bảng renameColumn(): đổi tên cột alterColumn(): sử cột dropColumn(): xóa cột createIndex(): tạo index dropIndex(): xóa index Active Record Mặc dù Yii DAO xử lý tất nhiệm vụ liên quan đến CSDL Nhưng việc sử dụng DAO dẫn đến số bất lợi cho việc lập trình: • Mất nhiều thời gian để xây dựng câu lệnh truy vấn thực công việc CRUD (tạo, đọc, cập nhật, xóa) nói chung • Khó bảo trì ứng dụng câu lệnh truy vấn SQL trộn lẫn chung với câu lệnh khác Để giải vấn đề trên, sử dụng Active Record Mỗi Active Record (AR) đại diện cho bảng (table) CSDL Các trường (field) bảng tương đương với thuộc tính AR Mỗi thực thể (instance) AR đại diện cho hàng (row) bảng Establishing DB Connection Để thiết lập kết nối protected/config/main.php đến CSDL, ta thiết lập return array( 'components'=>array( 'db'=>array( 'class'=>'system.db.CDbConnection', 'connectionString'=>'sqlite:path/to/dbfile', // turn on schema caching to improve performance // 'schemaCachingDuration'=>3600, ), cấu hình file JustLook Yii Framework Trang 25/31 ), ); Defining AR Class Một lớp (class) AR có cấu trúc sau: class Post extends CActiveRecord { public static function model($className= CLASS ) { return parent::model($className); } public function tableName() { return 'tbl_post'; } } Theo mặc định, tên lớp AR giống tên bảng (table) Sử dụng ghi đè (override) phương thức tableName() để thay đổi tên bảng cần Nếu bảng có khóa ta sử dụng phương thức primaryKey() để khai báo public function primaryKey() { return 'id'; // For composite primary key, return an array like the following // return array('pk1', 'pk2'); } Creating Record Để chèn hàng vào bảng CSDL, ta tạo thực thể AR, thiết lập giá trị thuộc tính (tương đương với giá trị trường bảng) cho Sau gọi phương thức save() để chèn Xem ví dụ: $post=new Post; $post->title='sample post'; $post->content='content for the sample post'; $post->create_time=time(); $post->save(); JustLook Yii Framework Trang 26/31 Reading Record Để đọc liệu bảng CSDL, ta sử dụng phương thức find(): // find the first row satisfying the specified condition $post=Post::model()->find($condition,$params); // find the row with the specified primary key $post=Post::model()->findByPk($postID,$condition,$params); // find the row with the specified attribute values $post=Post::model()->findByAttributes($attributes,$condition,$params); // find the first row using the specified SQL statement $post=Post::model()->findBySql($sql,$params); Using Transaction with AR $model=Post::model(); $transaction=$model->dbConnection->beginTransaction(); try { // find and save are two steps which may be intervened by another request // we therefore use a transaction to ensure consistency and integrity $post=$model->findByPk(10); $post->title='new post title'; $post->save(); $transaction->commit(); } catch(Exception $e) { $transaction->rollBack(); } Relational Active Record Có loại relationships: • • • • BELONGS_TO: quan hệ bảng A B one-to-many HAS_MANY: quan hệ bảng A B one-to-many HAS_ONE: quan hệ bảng A B many-to-one MANY_MANY: quan hệ bảng A B many-to-many Xem ví dụ, với sơ đồ ER sau: JustLook Yii Framework Ta khai báo lớp AR sau: class Post extends CActiveRecord { public function relations() { return array( 'author'=>array(self::BELONGS_TO, 'User', 'author_id'), 'categories'=>array(self::MANY_MANY, 'Category', 'tbl_post_category(post_id, category_id)'), ); } } class User extends CActiveRecord { public function relations() { return array( 'posts'=>array(self::HAS_MANY, 'Post', 'author_id'), 'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'), ); } } Trang 27/31 JustLook Yii Framework Trang 28/31 Để biết chi tiết Relational AR, vui lòng truy cập trang chủ Yii http://www.yiiframework.com/doc/guide/1.1/en/database.arr JustLook Yii Framework Trang 29/31 Extensions Library Classified extension • • • • • • • • • application component behavior widget controller action filter validator helper module Using extension Các extension (phần mở rộng) đặt thư mục protected/extensions ứng dụng Với extension tên xyz, sử dụng bí danh theo đường dẫn ext.xyz để truy cập đến extension Xem ví dụ: class SiteController extends CController { // public function actions() { return array( 'contact'=>‘ext.action.ContactAction', ); } // } protected/controllers/SiteController.php protected/extensions/action/ContactAction.php Với ví dụ trên, ta có extension ContactAction (extension contact) chứa thư mục protected/extensions/action Tại controller Site ta sử dụng action Contact cách khai báo phương thức actions() JustLook Yii Framework Trang 30/31 Creating extension Để tạo extension, trước hết ta cần ý đến vấn đề sau: • Một extension thành phần độc lập • Các tập tin extension cần tổ chức thư mục • Tên lớp (class) thuộc extension nên bắt đầu tiền tố (Yii kiến nghị sử dụng tiền tố “s”) (để phân biệt với class khác ứng dụng) • Một extension nên kèm tài liệu API hướng dẫn cài đặt • Một extension nên sử dụng giấy phép (license) thích hợp muốn chia cho cộng đồng Tùy vào loại extension để ta tạo extension phù hợp Ví dụ: extension action có cấu trúc class khác với extension validator Ta xem ví dụ sau: class MyValidator extends CValidator { protected function validateAttribute($model,$attribute) { $value=$model->$attribute; if($value has error) $model->addError($attribute,$errorMessage); } } Với ví dụ trên, ta tạo extension validator có tên MyValidator Một extenstion validator cần phài có phương thức validateAttribute class ContactAction extends CAction { protected function run() { // place the action logic here } } Ví dụ cho thấy extension action cần phải có phương thức run JustLook Yii Framework Trang 31/31 Để biết cấu trúc class loại extension, bạn truy cập vào trang chủ Yii (http://www.yiiframework.com/doc/guide/1.1/en/extension.create) ... CDbConnection::createCommand() Xem ví dụ: $rowCount=$command->execute(); $dataReader=$command->query(); $rows=$command->queryAll(); $row=$command->queryRow(); $column=$command->queryColumn(); $value=$command->queryScalar();... = Yii: :app( )-> db->createCommand() -> select(''*'') -> from(''tbl_user'') -> queryAll(); $user = Yii: :app( )-> db->createCommand() -> select(''id, username, profile'') -> from(''tbl_user u'') -> join(''tbl_profile... bảng A B one-to-many HAS_MANY: quan hệ bảng A B one-to-many HAS_ONE: quan hệ bảng A B many-to-one MANY_MANY: quan hệ bảng A B many-to-many Xem ví dụ, với sơ đồ ER sau: JustLook Yii Framework Ta

Ngày đăng: 30/06/2014, 21:15

Từ khóa liên quan

Mục lục

  • Introduction

  • Overview MVC

    • MVC

      • Model

      • View

      • Controller

      • Best MVC Practices

        • Model

        • View

        • Controller

        • CakePHP vs Yii

        • Yii Basic Workflow

        • Yii Components

          • 1. Application

          • 2. Controller

            • Action

            • Filter

            • 3. Component

              • Event

              • 4. Model

                • Working with model

                  • a) Validation Rules (Các quy tắc xác thực)

                  • b) Relational Active Record

                  • c) Một vài phương thức liên quan đến truy vấn CSDL

                  • 5. View

                  • 6. Widget

                  • Working with Database

                    • 1. Data Access Objects (DAO)

                      • Establishing Database Connection (Thiết lập kết nối CSDL)

                      • Executing SQL Statements (Thực thi câu lệnh truy vấn SQL)

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan