Saturday, February 28, 2015

Thử tạo một sample trang quản lý sử dụng câu lệnh oil generate của FuelPHP

Ở bài viết trước tôi đã giới thiệu về cách cài đặt và setting cơ bản của FuelPHP. Ở bài viết này tôi xin giới thiệu về cách tạo một trang quản lý bằng những câu lệnh tự động được tích hợp sẵn trong framework FuelPHP.

Đầu tiên, để tạo được một trang quản lý, chúng ta cần phải có xử lý xác thực người sử dụng. Để thực hiện việc xác thực này FuelPHP cung cấp cho chúng ta một package được gọi auth package, nó bao gồm cả Simpleauth và Ormauth.

Vậy Simpleauth và Ormauth khác nhau như thế nào ?
- Simpleauth thì chỉ có thông tin của user được lưu trong DataBase còn lại những setting liên quan đến quyền hạn như Group, role... thì được lưu trong file cài đặt.
- Ormauth chức năng cũng tương tự như Simpleauth nhưng chỉ khác nhau là những setting liên quan đến quyền hạn như Group, role... cũng được lưu trong DataBase.

Setting package
ở đây ta sử dụng 2 package:
- auth package (như đã thuyết minh ở trên)
- orm package (đây là package được sử dụng để FuelPHP tự động tạo code )

Trong file {ProjectDirectory}/fuel/app/config/config.php ta setting như sau:
 /**************************************************************************/
 /* Always Load                                                            */
 /**************************************************************************/
 'always_load'  => array(

  /**
   * These packages are loaded on Fuel's startup.
   * You can specify them in the following manner:
   *
   * array('auth'); // This will assume the packages are in PKGPATH
   *
   * // Use this format to specify the path to the package explicitly
   * array(
   *     array('auth' => PKGPATH.'auth/')
   * );
   */
  'packages'  => array(
                       'orm',
                       'auth',
  ),

               ......

Setting cho Simpleauth
Copy file simpleauth.php từ  {ProjectDirectory}/fuel/packages/auth/config/ đến {ProjectDirectory}/fuel/app/config/ và thay đổi setting như sau:
 /**
  * Groups as id => array(name => , roles => )
  */
 'groups' => array(
  /**
   * Examples
   * ---
   */
   -1   => array('name' => 'Banned', 'roles' => array('banned')),
   0    => array('name' => 'Guests', 'roles' => array()),
   1    => array('name' => 'Users', 'roles' => array('user')),
   50   => array('name' => 'Moderators', 'roles' => array('user', 'moderator')),
   100  => array('name' => 'Administrators', 'roles' => array('user', 'moderator', 'admin')),
 ),
        .......

 /**
  * Salt for the login hash
  */
 'login_hash_salt' => '08f8e0260c64418510cefb2b06eee5cd',

        .......

Setting Salt
Salt là gì ?
Nói đơn giản là thông tin được sử dụng để bảo mật cho mật khẩu, hoặc một số thông tin quan trọng khác. Cụ thể chi tiết về salt tôi sẽ giới thiệu ở bài viết khác.

Copy file auth.php từ  {ProjectDirectory}/fuel/packages/auth/config/ đến {ProjectDirectory}/fuel/app/config/ và thay đổi setting như sau:
......
return array(
 'driver' => 'Simpleauth',
 'verify_multiple_logins' => false,
 'salt' => '47bce5c74f589f4867dbd57e9ca9f808',
 'iterations' => 10000,
);
.....

Setting kết nối đến DataBase
{ProjectDirectory}/fuel/app/config/db.php
return array(
    'default' => array(
        'type' => 'mysqli',
        'connection'  => array(
            'persistent' => false,
        ),
        'identifier'    => '`',
        'table_prefix'  => '',
        'charset'       => 'utf8',
        'collation'     => 'utf8_general_ci',
        'enable_cache'  => true,
        'profiling'     => false,
        'readonly'      => false,
    ),
);

{ProjectDirectory}/fuel/app/config/development/db.php
return array(
    'default' => array(
        'connection'  => array(
            'hostname' => '127.0.0.1',
            'port'     => '3306',
            'database' => 'fuel_sample',
            'username' => 'fuel_sample',
            'password' => 'sample',
        ),
        'profiling' => true,
    ),
);

Trong Mysql tạo DB có tên fuel_sample như đã setting ở trên
//Tạo DB 
mysql> create database fuel_sample;
Query OK, 1 row affected (0.01 sec)

//Thiết lập quyền access cho user
mysql> grant all privileges on fuel_sample.* to fuel_sample@localhost identified by 'sample' with grant option;
Query OK, 0 rows affected (0.01 sec)

//kiểm tra lại user đã access đến DB được chưa
mysql> quit
Bye

$ mysql -u fuel_sample -p fuel_sample
Enter password:    <-------"sample"
 
$ show grants;
+--------------------------------------------------------------------------------------------------------------------+
| Grants for fuel_sample@localhost                                                                                   |
+--------------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'fuel_sample'@'localhost' IDENTIFIED BY PASSWORD '*18CEC0B12394150D87DD1C214207742851272BA6' |
| GRANT ALL PRIVILEGES ON `fuel_sample`.* TO 'fuel_sample'@'localhost' WITH GRANT OPTION                             |
+--------------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> show tables;
Empty set (0.00 sec)

Tạo table tự động cho DB chỉ định package auth
Di chuyển đến thư mục làm việc và chạy câu lệnh dưới đây:
$ cd ~/work/fuelphp
$ oil refine migrate --packages=auth
Performed migrations for package:auth:
001_auth_create_usertables
002_auth_create_grouptables
003_auth_create_roletables
004_auth_create_permissiontables
005_auth_create_authdefaults
006_auth_add_authactions
007_auth_add_permissionsfilter
008_auth_create_providers
009_auth_create_oauth2tables
010_auth_fix_jointables

File migrations.php được tạo ra trong {ProjectDirectory}/fuel/app/config/development/ và một số table được tạo trong DB
mysql> show tables;
+-----------------------+
| Tables_in_fuel_sample |
+-----------------------+
| migration             |
| users                 |
| users_clients         |
| users_providers       |
| users_scopes          |
| users_sessions        |
| users_sessionscopes   |
+-----------------------+
7 rows in set (0.00 sec)

Tạo account user quản lý
Sử dụng câu lệnh trong oil console để tạo hoặc thêm user quản lý
$ oil console
Fuel 1.7.2 - PHP 5.6.4 (cli) (Jan 23 2015 18:20:36) [Darwin]
>>> Auth::create_user('admin','passwd','admin@sample.jp','100');
1
>>> quit

Kiểm tra lại trong DB ở table: users thì ta sẽ thấy được thông tin của admin đã được tạo ra.
mysql> select * from users;
+----+----------+----------------------------------------------+-------+-----------------+------------+------------+----------------+------------+------------+
| id | username | password                                     | group | email           | last_login | login_hash | profile_fields | created_at | updated_at |
+----+----------+----------------------------------------------+-------+-----------------+------------+------------+----------------+------------+------------+
|  1 | admin    | NX9WjeRjdhdpml5xhWSsZLMP/XvF3MunnqhyTuGaNZM= |   100 | admin@sample.jp | 0          |            | a:0:{}         | 1425128534 |          0 |
+----+----------+----------------------------------------------+-------+-----------------+------------+------------+----------------+------------+------------+
1 row in set (0.00 sec)

Tạo model user từ DB
Chạy câu lệnh dưới đây thì model user sẽ tự động được tạo ra từ DB
$ oil refine fromdb:model users --no-migration
 Creating model: {ProjectDirectory}/fuelphp/fuel/app/classes/model/user.php

Tạo trang quản lý
Chạy câu lệnh dưới đây thì code của trang quản lý sẽ được tự động tạo ra
$ oil generate admin sample name:string[50] email:string[100] comment:string[512]
Creating controller: /Users/truong.tam/git/fuelphp/fuel/app/classes/controller/base.php
Creating controller: /Users/truong.tam/git/fuelphp/fuel/app/classes/controller/admin.php
Creating views: /Users/truong.tam/git/fuelphp/fuel/app/views/admin/template.php
Creating views: /Users/truong.tam/git/fuelphp/fuel/app/views/admin/dashboard.php
Creating views: /Users/truong.tam/git/fuelphp/fuel/app/views/admin/login.php
Creating migration: /Users/truong.tam/git/fuelphp/fuel/app/migrations/001_create_samples.php
Creating model: /Users/truong.tam/git/fuelphp/fuel/app/classes/model/sample.php
Creating controller: /Users/truong.tam/git/fuelphp/fuel/app/classes/controller/admin/sample.php
Creating view: /Users/truong.tam/git/fuelphp/fuel/app/views/admin/sample/index.php
Creating view: /Users/truong.tam/git/fuelphp/fuel/app/views/admin/sample/view.php
Creating view: /Users/truong.tam/git/fuelphp/fuel/app/views/admin/sample/create.php
Creating view: /Users/truong.tam/git/fuelphp/fuel/app/views/admin/sample/edit.php
Creating view: /Users/truong.tam/git/fuelphp/fuel/app/views/admin/sample/_form.php
Creating view: /Users/truong.tam/git/fuelphp/fuel/app/views/template.php

//Thực hiện lệnh migrate để tạo table: samples trong DB
$ oil refine migrate
Performed migrations for app:default:
001_create_samples

Bây giờ access vào link dưới đây để xem kết quả
http://localhost/fuelphp/admin/

Nhập thông tin của admin/passwd sẽ di chuyển đến màn hình quản lý

Đến đây thì việc tạo trang quản lý tự động bằng những câu lệnh oil generate của FuelPHP kết thúc, nếu chúng ta muốn thay đổi design hoặc thay đổi ngôn ngữ hiển thị... thì có thể sửa code theo ý của mình.

No comments:

Post a Comment