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.

Thursday, February 5, 2015

Ghi chú về thứ tự cài đặt FuelPHP và những setting ban đầu

Tôi là người mới nhập môn FuelPHP.
Sau đây là những ghi chú lại về thứ tự cài đặt FuelPHP và những setting ban đầu.

Trình tự cài đặt FuelPHP trên Mac OS
1. Cài đặt oil
$ curl get.fuelphp.com/oil | sh

Kiểm tra lại việc cài đặt có thành công hay chưa bằng câu lệnh dưới đây.
$ which oil
/usr/bin/oil

2. Cài đặt FuelPHP
- Tạo folder làm việc 
*)vi dụ~/work/fuelphp
$ cd
$ mkdir work
$ cd work

- Cài đặt FuelPHP
Thực hiện câu lệnh dưới đây thì ta sẽ download được phiên bản release mới nhất của FuelPHP từ GitHub.
$ oil create fuelphp

3. Thiết lập cho apache
- Trong Mac os thì mặc định đã cài đặt sẵn apache rồi nên ta có thể sử dụng luôn mà không cần cài đặt lại.
- Đường dẫn làm việc mặc định là:
/Library/WebServer/Documents
- Từ apache muốn xử lý đến fuelphp được thì ta cần phải thiết lập symbolic link
$ ln -s ~/work/fuelphp/public fuelphp

4. Kiểm tra lại hoạt động của FuelPHP
- Từ browser access tới http://localhost/fuelphp/
Nếu trang Welcome của FuelPHP hiện ra thì việc cài đặt kết thúc.


Tuy nhiên, Khi access tới trang  http://localhost/fuelphp/ thì xuất hiện lỗi như dưới đây, cho nên ban đầu chúng ta phải cài đặt lại Timezone.
・Thông tin Error:
-----------
Fuel\Core\PhpErrorException [ Error ]:
date_default_timezone_get(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.
-----------

・Thiết lập Timezone
Mở file dưới đây
/work/fuelphp/fuel/app/config/config.php

Ở dòng 97 cài đặt giá trị mặc định của Timezone.
Ví dụ:
'default_timezone'   => 'Asia/Tokyo',

Lưu lại thiết lập trên, access lại link http://localhost/fuelphp/ thì trang Welcome của FuelPHP sẽ hiển thị ra màn hình.

Tôi đã sử dụng thử Rocketeer

  • Mục đích muốn tiến hành
Sử dụng công cụ deploy của PHP là Rocketeer để deploy một ứng dụng đặt trên GitHub từ môi trường A đến môi trường remote B.

  • Môi trường đã sử dụng thử (Môi trường A, Môi trường B)
CentOS 6.5
PHP 5.4

# Dưới đây là những thao tác tiến hành trên môi trường A
  • Cài đặt composer
 # curl -sS https://getcomposer.org/installer | php -d detect_unicode=Off
 # mv composer.phar /usr/local/bin/composer

  • Cài đặt Rocketeer 
# cd /{project-folder}
# composer require anahkiasen/rocketeer:dev-master
 // Cứ nhấn nút Enter bằng giá trị mặc định 

  • Thiết lập Rocketeer
# cd /{project-folder}
# cd .rocketeer
# vi scm.php
 // Cập nhật lại repository, username, password của GitHub
# vi config.php
 // Cập nhật lại host, username, password của môi trường B

# vi remote.php
 // Cập nhật lại root_directory, files của môi trường B

  • Deploy bằng Rocketeer
# cd /{project-folder}
# ./vendor/bin/rocketeer deploy

  • Kiểm tra lại kết quả deploy
# cd /{project-folder}
# cd .rocketeer/logs
# less production--yyyyMMdd.log

Wednesday, February 4, 2015

Trình tự thiết lập Swift + Realm DB bằng CocoaPods


Cài đặt CocoaPods trên Mac 

1. Sử dụng gem để cài đặt CocoaPods

$ sudo gem install cocoapods
Vì cần phiên bản trước khi release phiên bản beta, nên sẽ cài đặt kết hợp.

$ gem install cocoapods --pre


2. Khởi động lại Terminal

Đừng quên, sau khi khởi động lại xong cần kiểm tra lại version xem đã cài đặt đúng chưa.

$ pod -v

3. set Up

$ pod setup

 

Tạo Project mới trong Xcode 

 Trong Xcode tạo một project mới, chọn ngôn ngữ code là Swift.
 Để dễ thuyết minh tôi đặt tên project này là Sample.


Đưa CocoaPods vào trong Project của Xcode 

 1. Di chuyển đến đường dẫn đã tạo bằng Xcode


$ cd project root directory
$ ls -la
 Sample
 Sample.xcodeproj
 SampleTests


 2. Initialization CocoaPods


$ pod init
Podfile sẽ được tạo ra.


 3. Thay đổi Podfile

target 'Sample', exclusive: true do
 pod 'Realm'
end

target 'SampleTests', exclusive: true do
    pod 'Realm/Headers'
end


Sử dụng block chúng ta có thể phân ra từng pod cài đặt trong từng Target khác nhau.

Nếu exclusive: true thì chúng ta chỉ cài đặt được một pod duy nhất trong block.

4. Trong đường dẫn mà đã khởi tạo pod (pod init ) thực hiện câu lệnh dưới đây 

$ pod install


 5.  Đóng project của Xcode lại, và mở project có tên là Sample.xcworkspace

Đến thời điểm này thì kết thúc việc thiết lập Realm DB
.



Sử dụng Realm DB bằng Swift

Realm DB cài đặt bằng CocoaPods thì được viết bằng ngôn ngữ Objective-C. Để trong project của Swift cũng sử dụng được thì chúng ta phải thêm file Bridging Header vào.

Thêm file head bên dưới vào trong project

Sample-Bridging-Header.h


 1.Thêm hàng dưới đây


#import <Realm/Realm.h>


 2. Vào Build Settings của project -> swift compiler

Trong mục Objecctive-C Bridging header
 thêm vào file Sample/Sample-Bridging-Header.h 

Chú ý 
rất dễ sai đường dẫn path. Tuỳ vào môi trường khác nhau mà sẽ có phân cấp khác nhau.


3. Kiểm tra lại 

Trong file của swift viết vào nội dung dưới đây

RLMObject()
Nếu không thấy xuất hiện lỗi thì việc thiết lập đã thành công.



Người viết: Takanori Matsumoto  
Nguồn: Swift + Realm DB をCocoaPodsで導入する手順

Tuesday, February 3, 2015

Bắt đầu với WebComponents

Xin chào. Tôi là naoto.higuchi@mulodo.com
Trong bài viết này tôi xin giới thiệu về những yếu tố kĩ thuật đang được sử dụng trong Qword. Đầu tiên chúng ta sẽ bắt đầu với WebComponents.

WebComponents là gì ?
  Nói vắn tắt, đó là một tiêu chuẩn Web để chia sẻ, để tạo ra một thành phần giao diện tùy chỉnh cho người dùng . Nó bao gồm các yếu tố sau đây.
 • Template
 • Custom Elements
 • Shadow DOM
 • HTML Imports


Polyfill
  Rất tiếc là trình duyệt Browser để thực hiện cho việc này không có nhiều, cho nên chúng ta cần phải sử dụng JavaScript Polyfill.

Polyfill thì dễ quản lí bằng bower (bỏ qua phần thuyết minh cho bower).
$ bower install webcomponentsjs
Trong html viết vào đoạn code dưới đây thì sẽ load được polyfill của WebComponents. Trong trường hợp trình duyệt Browser không thực hiện được những kĩ thuật cơ bản của WebComponents, thì tôi phải load polyfill.
<script>
if ('registerElement' in document
    && 'createShadowRoot' in HTMLElement.prototype
    && 'import' in document.createElement('link')
    && 'content' in document.createElement('template')) {
    // We're using a browser with native WC support!
  } else {
    document.write('<script src="bower_components/webcomponentsjs/webcomponents.min.js"><\/script>');
  }
</script>
Polymer
  WebComponents là một yếu tố kĩ thuật cơ bản có level thấp, trong phát triển thực thế thì hầu như chúng ta không tương tác trực tiếp với WebComponents, mà sử dụng những thư viện của JavaScript được tạo thành dựa trên nền tảng của WebComponents. Tiêu biểu đến thời điểm hiện tại có các thư viện như Polymer và X-TAG. Qword thì đang sử dụng thư viện Polymer.

Trong bài viết tiếp theo, nếu cần thiết tôi sẽ giải thích thêm về WebComponents, và giải thích về Polymer.


Người viết: Naoto Higuchi
Nguồn: WebComponentsを始めよう