Hướng dẫn alias php artisan - hay còn gọi là nghệ nhân php

Trong bài viết này mình sẽ giới thiệu về facade và alias trong laravel

Môi trường khảo sát

Trong bài viết này môi trường khảo sát sẽ theo version sau của laravel

Laravel 5.5.x

Những phiên bản cũ có thể khác với phiên bản mới nhất, thực tế là nó khác nhau. Hãy chú ý đến điểm đó

Ví dụ sử dụng Facade

Ví dụ trong laravel bạn muốn ghi log vào laravel.log thì bạn phải sử dụng Log

Trên ví dụ trên bạn thấy việc ghi log chỉ việc sử dụng class \Log và phương thức static của nó, vậy class Log này nó được load vào khi nào?

Giới thiệu về Facade

Ở ví dụ thực ra class Log chính là \Illuminate\Support\Facades\Log, tuy nhiên ở trên bạn có thể gọi được như trên là thông qua alias

Trong khi implement class Log, bạn xem code sẽ có hàm sau

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   

Code tạo 1 facade trông rất đơn giản, vậy thì việc gọi những hàm ::info, ::warning, ::debug ... ở đâu, vì những hàm này đều là những hàm public , vậy bạn hãy lên trên class cha Facade Bạn sẽ thấy hàm sau, nó sẽ đóng vai trò gọi các hàm publicFacade Bạn sẽ thấy hàm sau, nó sẽ đóng vai trò gọi các hàm public

     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }

Hàm __callStatic sẽ thực hiện gọi một phương thức trong class được nạp vào Facade(chỉ phương thức default, public, static), trên hàm trên bạn thấy có gọi hàm getFacadeRoot, code của hàm này như dưới__callStatic sẽ thực hiện gọi một phương thức trong class được nạp vào Facade(chỉ phương thức default, public, static), trên hàm trên bạn thấy có gọi hàm getFacadeRoot, code của hàm này như dưới

     /**
     * Get the root object behind the facade.
     *
     * @return mixed
     */
    public static function getFacadeRoot()
    {
        return static::resolveFacadeInstance(static::getFacadeAccessor());
    }
    
     /**
     * Resolve the facade root instance from the container.
     *
     * @param  string|object  $name
     * @return mixed
     */
    protected static function resolveFacadeInstance($name)
    {
        if (is_object($name)) {
            return $name;
        }

        if (isset(static::$resolvedInstance[$name])) {
            return static::$resolvedInstance[$name];
        }

        return static::$resolvedInstance[$name] = static::$app[$name];
    }

Trong hàm trên sẽ thực hiện tìm kiếm những instance từ DI container đã được đăng ký trong application dựa vào name name này sẽ được đăng ký ở hàm getFacadeAccessorname name này sẽ được đăng ký ở hàm getFacadeAccessor

Giới thiệu về Alias

Trong cấu trúc laravel bạn sẽ khai báo các alias ở trong config/app.phpconfig/app.php

    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        ...
        'Log' => Illuminate\Support\Facades\Log::class,
        ...

Các alias được đăng ký và load dự trên function spl_autoload_register, các aliases được load ở trong class AliasLoader.php

     /**
     * Prepend the load method to the auto-loader stack.
     *
     * @return void
     */
    protected function prependToLoaderStack()
    {
        spl_autoload_register([$this, 'load'], true, true);
    }

Việc sử dụng facade trong laravel giống như là các util rất là dễ dàng, bên cạnh đó có thể viết các helper dùng facade

Ví dụ

Sau đây là ví dụ tạo 1 facade trong laravel https://github.com/ngodinhngoc/laravel_tip/pull/1/files

Các bạn có thể tham khảo cách tạo 1 facade, nó cũng gần giống như là tạo 1 helper trong laravel!

Bash aliases là shortcut thêm vào 1 file cho phép bạn tham chiếu đến 1 lệnh khác thông qua nhiều từ dễ nhớ, từ viết tắt, hoặc các kí tự. Ví dụ, nếu bạn sử dụng Git, bạn có thể chạy

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
9 rất nhiều lần trong ngày, vậy để tiết kiệm thời gian bạn có thể sử dụng alias
     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
0 thay vì
/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
9, và nó sẽ tự động gọi đến câu lệnh tương ứng.

Mỗi người có 1 mẫu shortcut khác nhau, ví dụ,

     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
2,
     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
3, hoặc
     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
4 dành cho câu lệnh
     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
5. Có 1 alias độc mà ít người chia sẻ là alias
     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
6:

nah='git reset --hard;git clean -df'

Câu lệnh trên thật sự rất hay và để chứng minh nó hoạt động thế nào, giả sử bạn bắt đầu làm 1 vài feature mới, có thể bạn đã thêm vào 1 vài file mới, và sau giờ nghỉ trưa, bạn quyết định tất cả những cái bạn vừa làm là sai. Khi đó bạn sử dụng

     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
6, nó sẽ reset toàn bộ code của bạn về trạng thái như lúc chưa sửa, và xóa toàn bộ file mà git không biết. Rất thuận tiện và hữu dụng!

Làm thế nào để tạo Bash Aliases của riêng bạn

Dành cho những người mới tạo bash aliases, cách làm rất đơn giản. Đầu tiên, mở file

     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
8 trong thư mục home của bạn bằng 1 text editor. Bỏ comment hoặc thêm vào những dòng sau:

if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi

Nó sẽ load file

     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
9 nếu file đó tồn tại, vậy nên bạn có thể để tất cả aliases vào trong file đó để có thể dễ dàng chia sẻ và update. Cuối cùng, tạo file
     /**
     * Get the root object behind the facade.
     *
     * @return mixed
     */
    public static function getFacadeRoot()
    {
        return static::resolveFacadeInstance(static::getFacadeAccessor());
    }
    
     /**
     * Resolve the facade root instance from the container.
     *
     * @param  string|object  $name
     * @return mixed
     */
    protected static function resolveFacadeInstance($name)
    {
        if (is_object($name)) {
            return $name;
        }

        if (isset(static::$resolvedInstance[$name])) {
            return static::$resolvedInstance[$name];
        }

        return static::$resolvedInstance[$name] = static::$app[$name];
    }
0 và thêm những dòng sau như những alias đầu tiên của bạn:

alias art="php artisan"

Lưu file lại, và chạy lệnh sau ở Terminal:

0

Từ đây bạn có thể gõ

     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
4 và nó sẽ tự động chạy lệnh
     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
5. Nhớ rằng bất cứ khi nào bạn chỉnh sửa file
     /**
     * Handle dynamic, static calls to the object.
     *
     * @param  string  $method
     * @param  array   $args
     * @return mixed
     *
     * @throws \RuntimeException
     */
    public static function __callStatic($method, $args)
    {
        $instance = static::getFacadeRoot();

        if (! $instance) {
            throw new RuntimeException('A facade root has not been set.');
        }

        return $instance->$method(...$args);
    }
9 bạn sẽ phải source lại hoặc reset Terminal để nó có thể sử dụng được

Laravel Bash Aliases từ cộng đồng

Dưới đây là 1 danh sách alias đang được cộng đồng Laravel sử dụng

WaveHack

1

bmadigan

2

Tainmar

3

Mohamed Said

4

Jeffrey Way

5

Bill Mitchell

6

Jesús Amieiro

7

Piotr

8

freekmurze

9

paulredmond

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
0

TJ Miller

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
1

sebastiaanluca

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
2

Alexander Melihov

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
3

jordonbaade

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
4

Deleu

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
5

curieuxmurray

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
6

wilburpowery

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
7

waunakeesoccer1

/**
 * @see \Illuminate\Log\Writer
 */
class Log extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return LoggerInterface::class;
    }
}
   
8

https://laravel-news.com/bash-aliases https://laravel-news.com/@ericlbarnes