Wednesday, April 22, 2015

Work with Laravel ViewComposer

This video will help you to work correctly with Laravel ViewComposer
Thank laracasts.com for sharing

https://laracasts.com/series/laravel-5-fundamentals/episodes/25


Wednesday, April 1, 2015

Create folder with Laravel Filesystem

Cách tạo một cây thư mục đơn giản với Laravel Filesystem
Sử dụng hàm: File::makeDirectory()

Ví dụ:
Để tạo 1 folder với chmod default
$result = File::makeDirectory('/path/to/directory');

Hoặc để tạo 1 cây thư mục với chmod 0755
$result = File::makeDirectory('/path/to/directory', 0775, true);

Friday, February 27, 2015

Hướng dẫn tạo View Composer đơn giản với Laravel 5

Bạn có 1 menu hay một box nào đó hiển thị ở nhiều trang khác nhau. Để tránh lặp code và code template tường minh hơn , chúng ta có thể dùng View Composer của Laravel để giải quyết vấn đề này.

Sau đây là hướng dẫn tạo 1 View Composer đơn giản với Laravel 5

1. Tạo View Composer
- Laravel không có sẵn folder ViewComposer --> Bạn có thể tự tạo: App\Http\ViewComposers
- Tạo class MyTestComposer với nội dung bên dưới
- Code nghiệp vụ trong hàm composer và truyền tham số ra template. Ví dụ: Truyền biến $testVariable ra template như bên dưới.
<?php  //file: MyTestComposer.php
namespace App\Http\ViewComposers;

use Illuminate\Contracts\View\View;

class MyTestComposer {
//    protected $param;

  /**
   * Create a new  composer.
   * @return void
   */
  public function __construct() {
    // Dependencies automatically resolved by service container...
  }

  /**
   * Bind data to the view.
   *
   * @param  View  $view
   * @return void
   */
  public function compose(View $view) {
    // Code here
    $view->with('testVariable', 'Value from MyTest Composer');
  }
}
2. Tạo template để xử lý dữ liệu mà ViewComposer đẩy ra
Ở đây tôi tạo template theo đường dẫn sau: (tùy thuộc vào cách quy hoạch project của các bạn)  resources/view/frontend/default/myComposer.blade.php
Nội dung template, ví dụ:
MyComposer Content <br />
{{ $testVariable }}  -- Hien thi gia tri bien $testVariable
3. Định nghĩa  ComposerServiceProvider
- Bạn cần tìm hiểu thêm về Provider:  http://laravel.com/docs/5.0/providers
- Tạo class ComposerServiceProvider trong thư mục app/Providers với nội dung sau:
- Đoạn code bôi đậm chính là khai báo việc template nào sẽ sử dụng ViewComposer của bạn? Ở đây là template layout chung của website. Bạn cũng có thể nhúng nó vào bất kỳ template nào tùy vào nghiệp vụ của hệ thống (home, news detail, etc ... )
Ví dụ:
View::composer(['frontend.home', 'frontend.newsDetail'], 'App\Http\ViewComposers\MyTestComposer');
<?php  // file: ComposerServiceProvider.php
namespace App\Providers;

use View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider {

  /**
   * Register bindings in the container.
   *
   * @return void
   */
  public function boot() {
    // Using class based composers...
    View::composer('frontend.layout', 'App\Http\ViewComposers\MyTestComposer');

    // Using Closure based composers...
//        View::composer('frontend.layout', function()
//        {
//          $menu = 'A|B|C';
//          $view->with('menus', $menus);
//        });
  }

  /**
   * Register
   *
   * @return void
   */
  public function register() {
    //
  }
}
4.Sau khi định nghĩa ComposerServiceProvider bạn cần khai báo vào mảng providers để hệ thống thực thi.
Sửa file: config/app.php
Thêm đoạn code bôi đậm vào mảng providers. (Tôi rút gọn các đoạn code mặc định)
'providers' => [
        /*
         * Laravel Framework Service Providers...
         */
        ...... Default Providers

        /*
         * Application Service Providers...
         */
        ...... Default Providers

        'App\Providers\ComposerServiceProvider'
    ],
5. Include template
Ở trên tôi khai báo template layout sẽ dùng MyTestComposer. Nghĩa là các tham số tương ứng của MyTestComposer cũng sẽ được truyền ra view tương ứng.
Việc cuối cùng cần làm là include template xử lý các tham số của MyTestComposer này
Mở file: resources/views/frontend/layout.blade.php include như sau
@include('frontend.default.myComposer')
6. Done.
Chúc các bạn có những dòng code đẹp và tường minh với Laravel :)
Refer:
- http://laravel.com/docs/5.0/views
- http://laravel.com/docs/5.0/providers
- http://laravel.com/docs/5.0/templates
- http://heera.it/laravel-4-view-composer-master-layout#.VPENkIusV1k

Laravel55555.

Sunday, February 1, 2015

Return Json và Download file với HTTP Responses


Việc xử lý code download file hay trả về json sẽ rất nhanh gọn

Creating A JSON Response
(Tự động set Content-Type header = "application/json"

return response()->json(['name' => 'Steve', 'state' => 'CA']);
Creating A JSONP Response
return response()->json(['name' => 'Steve', 'state' => 'CA'])
                 ->setCallback($request->input('callback'));
Creating A File Download Response
return response()->download($pathToFile);

return response()->download($pathToFile, $name, $headers);

Một số hàm xử lý HTTP request

Tương tự các framework khác, bạn có thể lấy giá trị từng biến, set default, hoặc lấy 1 mảng các giá trị truyền lên.
Một số hàm sau rất hữu ích trong 1 số trường hợp đặc biệt

Chỉ lấy một số input nhất định: 
$input = Request::only('username', 'password');

$input = Request::except('credit_card');
Hàm làm việc với 1 mảng các inputs: sử dụng dấu chấm "."
$input = Request::input('products.0.name');
Old input: Giữ lại input cho tới request tiếp theo (giống FLASH của symfony)
Ví dụ: 
Request::flashOnly('username', 'email');

Request::flashExcept('password');
Flash & Redirect 
return redirect('form')->withInput();

return redirect('form')->withInput(Request::except('password'));
Lấy giá trị old input từ flash 
$username = Request::old('username');
Get URI & URL
$uri = Request::path();
$url = Request::url();
Kểm tra đường dẫn Matches với 1 Pattern
if (Request::is('admin/*'))
{
    //
}
Source: http://laravel.com/docs/master/requests

Thursday, January 29, 2015

Routing mạnh mẽ, linh hoạt

Đơn giản, linh hoạt và bảo mật hơn với routing.
Định nghĩa rõ ràng phương thức tương tác, các biến, validate CSRF token, validate tham số trên URL ngay ở bước khai báo routing
Route::post('foo/bar', function()
{
    return 'Hello World';
});

Route::put('foo/bar', function()
{
    //
});

Route::delete('foo/bar', function()
{
    //
});
Regular Expression Parameter Constraints
Route::get('user/{name}', function($name)
{
    //
})
->where('name', '[A-Za-z]+');

Route::get('user/{id}', function($id)
{
    //
})
->where('id', '[0-9]+');
Passing An Array Of Constraints
Route::get('user/{id}/{name}', function($id, $name)
{
    //
})
->where(['id' => '[0-9]+', 'name' => '[a-z]+'])
Defining Global Patterns
Định nghĩa Global Patterns để applied cho nhiều routing. Ví dụ dưới là định nghĩa biến số nguyên "id"
$router->pattern('id', '[0-9]+');
Route::get('user/{id}', function($id)
{
    // Only called if {id} is numeric.
});
Khai báo tên cho Routing, tiện lợi cho việc generate ra URL. 
Route::get('user/profile', ['as' => 'profile', 'uses' => 'UserController@showProfile']);
$url = route('profile');

$redirect = redirect()->route('profile');
Trên đây là 1 số tính năng thường dùng.
Tham khảo thêm tại đây: http://laravel.com/docs/master/routing

Caching Query

Cache kết quả truy vấn đơn giản với method "remember "
Ví dụ: cache kết quả 10 phút. Hệ thống sẽ sử dụng cache driver mà bạn cấu hình (file cache, database cache, memcache, redis, ...)
$users = DB::table('users')->remember(10)->get();

Source: http://laravel.com/docs/4.2/queries#caching-queries
Tìm hiểu thêm về Cache: http://laravel.com/docs/4.2/cache

Truy vấn nâng cao với Laravel query builder

Truy vấn CSDL thuận tiện và mềm dẻo, có thể hỗ trợ hầu hết các thao tác với CSDL và support nhiều loại CSDL khác nhau.
Sau đây là 1 số cách truy vấn hữu dụng trong 1 số tình huống phức tạp

1. JOINS

Basic Join Statement
DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.id', 'contacts.phone', 'orders.price')
            ->get();
Left Join Statement
DB::table('users')
        ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
        ->get();
Advanced join clauses
DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
        })
        ->get();
Trường hợp muốn sử dụng thêm điều kiện "Where" trong lệnh JOINS


DB::table('users')
        ->join('contacts', function($join)
        {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();

2. ADVANCED WHERE

Parameter Grouping


DB::table('users')
            ->where('name', '=', 'John')
            ->orWhere(function($query)
            {
                $query->where('votes', '>', 100)
                      ->where('title', '<>', 'Admin');
            })
            ->get();
Câu lệnh truy vấn sẽ như sau:
select * from users where name = 'John' or (votes > 100 and title <> 'Admin')


Exists Statements
DB::table('users')
            ->whereExists(function($query)
            {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();
Câu lệnh truy vấn sẽ như sau:
select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)

3. KẾT HỢP TRUY VẤN THUẦN (RAW)
Đôi khi bạn buộc phải lồng các truy vấn thuần vào câu lệnh như dưới đây, hãy lưu ý để tránh bị lỗi SQL Injection
$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();
Source: http://laravel.com/docs/4.2/queries

Database configuration - Read / Write Connections

Cấu hình kết nối tới 2 database Mysql: 1 để đọc và 1 để ghi.
Có thể override các giá trị ở mảng chính (nếu cần)
'mysql' => array(
    'read' => array(
        'host' => '192.168.1.1',
    ),
    'write' => array(
        'host' => '196.168.1.2', 
    ),
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Wednesday, January 28, 2015

LARAVEL FRAMEWORK

Laravel Framework 4, vừa chỉ ra mắt vào cuối tháng 5 - 2013. Tuy vậy, PHP Framework này đã nhanh chóng có được một cộng đồng rất lớn trong thế giới các Framework của ngôn ngữ lập trình PHP

Sự tinh tế của Laravel nằm ở chỗ bắt kịp được xu hướng công nghệ mà điểm nhấn ở đây là các tính năng mới trong các phiên bản PHP 5.3 trở lên. Điều đó được thể hiện qua khái niệm namespacecomposer, closure và rất nhiều những tiêu chuẩn trong design pattern được áp dụng trên nền tảng framework này. Đồng thời, với cách hướng dẫn đơn giản và dễ tiếp cận giống với Codeigniter Framework đã khiến người dùng thích ngay từ lần đầu "hẹn hò" với framework này.

Laravel 4 cũng có sự tích hợp của một phần trong thư viện symfony và áp dụng triệt để mô hình ORM với khái niệm liên quan đến Eloquent class. Đồng thời, nó cũng giải quyết được những vấn đề mà các framework khác đang mắc phải. Chẳng hạn như master layout, mô hình xử lý với ORM, event model,....

Cuối năm 2013, khi các chuyên gia tổng hợp về sự tăng trưởng của laravel framework trong những tháng cuối năm thì chúng ta có thể thấy Laravel vượt lên dẫn đầu trước các PHP framework lớn mạnh khác một cách ngoạn mục, khi tỷ lệ % của laravel chiếm tới những 25,85%, trong khi các framework đình đám khác lại tụt giảm thê thảm như zend framework 2 chỉ còn 4,51% là 1 ví dụ.
Thống kê PHP Framework trong cuối năm 2013
Có thể bảng thống kê trên đây chưa thể mang một ý nghĩa khách quan cho thấy laravel tăng trưởng hoàn toàn, nhưng thêm 1 cơ sở để các bạn tin rằng laravel đã đảo chiều ngoạn mục đó là dựa vào thống kê trên mạng xã hội dành cho lập trình viên toàn thế giới github. Bạn có thể nhận thấy qua hình chụp bên dưới.
Thống kê PHP Framework trong github
Với con số 8341 sao và dẫn đầu trong các danh sách PHP Framework, điều nay cho thấy "có 1 sự quan tâm không hề nhẹ" của giới coder đối với Laravel Framework.

Chưa hết, quyển sách Codebright viết về Laravel Framework 4.x của tác giả Dayle Rees cũng nhanh chóng làm mưa làm gió trên thị trường, chỉ vỏn vẹn vài tháng sách đã bán được tận 3295 bản (ebook). Một con số hằng mơ của nhiều tác giả viết về công nghệ nhất là với thị trường ebook mua 1 mà share 10 như hiện nay. Hiện quyển sách này liên tục đứng vào vị trí bestselling trong nhiều tuần qua tại hãng phát hành ebook Leanpub.
Top 10 quyển sách bán chạy nhất trong tuần
Trong khi quyển sách zend framework 2: Web Development with Zend Framework 2 của tác giả Michael Romer dù đã phát hành từ cuối năm 2012 nhưng đến nay cũng mới chỉ bán được 962 bản đọc.

Nguồn: QHonline