라벨의 가장 위대한 마술: 마술

21709 단어 magiclaravelphp

묵문(Mervyn Chan)의 Unsplash 사진
Laravel은 PHP의 사용을 새로운 수준으로 끌어올려 다음 프로젝트에 탁월한 개발 체험(DX)을 제공합니다.그래서 어떤 사람들은 그것을'마법'이라고 부른다.
오늘, 나는 너희들에게 라벨의 기교, 마술을 보여줄 것이다.

신기한 방법이 뭐예요?


중요한 것은 신기한 방법이 Laravel만의 것이 아니라 어떤 PHP 앱에서도 사용할 수 있다는 것을 이해하는 것이다.Laravel에는 마침 마법 방법의 가장 재미있는 용례가 있다.
Magic 메서드는 PHP에서 선언된 모든 클래스에서 사용할 수 있는 메서드로 클래스에서 추가 기능을 구현하는 메서드를 제공합니다.
여기에는 좋은 정의가 있다.

magic methods will never directly be called by the programmer – actually, PHP will call the method 'behind the scenes'. This is why they are called 'magic' methods – because they are never directly called, and they allow the programmer to do some pretty powerful things.


총 15가지 신기한 방법이 있다.
class MyClass
{
    public function __construct() {}

    public function __destruct() {}

    public function __call() {}

    public function __callStatic() {}

    public function __get() {}

    public function __set() {}

    public function __isset() {}

    public function __unset() {}

    public function __sleep() {}

    public function __wakeup() {}

    public function __toString() {}

    public function __invoke() {}

    public function __set_state() {}

    public function __clone() {}

    public function __debuginfo() {}
}
만약 PHP로 대상을 대상으로 프로그래밍을 한 적이 있다면, 당신은 틀림없이 __construct 방법을 알아볼 것이다. 이것도 신기한 방법이다.그래서 마법을 계속 사용하고 있어!
모든 매직 방법은 __ 접두사로 되어 있음을 알 수 있습니다.
오늘 우리는 이 모든 것을 토론하지 않고, 전체 Laravel 코드 라이브러리에서 사용하는 재미있는 코드만 토론할 것이다.만약 다른 사람이 당신에게 관심이 있다면, 언제든지 아래의 문서를 보십시오👇
PHP: Méthodes magiques - Manual

라빌은 마법을 어떻게 사용하는지


얻기()


라빌의 모델은 정말 특이해요.이들은 속성 데이터를 클래스의 직접 속성으로 저장하지 않고 속성protected $attributes에 저장한다. 이 속성은 모델이 가지고 있는 모든 데이터의 관련 수조이다.
간단한 PHP 클래스와 액세스 속성의 Laravel 모델 간의 차이점을 살펴보겠습니다.
<?php

/**
 * A normal user class in PHP (without Laravel) will be just a class with the said attributes
 */
class NormalUser
{
    public $firstName = 'Alice';
}

$normalUser = new NormalUser;

$normalUser->firstName; // Will return 'Alice'
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * A user class in Laravel
 */
class LaravelUser extends Model
{
    /**
     * Note that we store all the attributes data in one and single array
     */
    protected $attributes = [
        'firstName' => 'Alice',
    ];
}

$laravelUser = new LaravelUser;

$laravelUser->firstName; // Will return 'Alice' as well
위의 PHP와 Laravel류의 행동이 완전히 같다는 것을 알 수 있습니다.그러나 Laravel의 경우 속성은 일반 PHP처럼 저장되지 않고 $attributes라는 속성에 집중된다.그럼에도 불구하고, 우리는 여전히 정확한 데이터에 접근할 수 있지만, 어떻게 접근할 수 있습니까?__get 신기한 방법 때문에, 이 모든 것은 가능하다.하나의 예에서 우리 자신의 간략한 버전을 실현해 봅시다.
<?php

class NormalUser
{
    /**
     * We declare the attributes that same way as in Laravel
     */
    protected $attributes = [
        'firstName' => 'Alice',
    ];

    /**
     * The function __get receive one parameter
     * which will be the name of the attribute you want to access
     * in this case $key = "firstName"
     */
    public function __get(string $key)
    {
        return $this->attributes[$key];
    }
}

$normalUser = new NormalUser;

$normalUser->firstName; // Will return 'Alice'
우리 해냈어!🎉
클래스에서 일치하는 이름을 가진 속성을 찾을 수 없을 때만magic 방법__get을 호출할 수 있음을 주의해야 한다.이것은 PHP가 클래스에서 ask 속성을 찾을 수 없을 때 호출하는 반환 방법입니다.따라서 아래의 예에서magic 방법__get을 전혀 사용하지 않는다.
<?php

class NormalUser
{
    public $firstName = 'Bob';

    protected $attributes = [
        'firstName' => 'Alice',
    ];

    public function __get($key)
    {
        return $this->attributes[$key];
    }
}

$normalUser = new NormalUser;

/**
 * Will return 'Bob' as the attribute exists in the class
 * so the magic method __get doesn't get call in this case
 */
$normalUser->firstName;
막후에서 발생한 일이 훨씬 많다.라벨의 모델 사용__get의 정확도를 더 알고 싶다면 아래의 원본 코드를 보십시오.
laravel/framework

__set()


설정하려는 속성이 클래스에 표시되지 않았을 때magic 방법 __set 을 사용합니다.일반 PHP 클래스와 Laravel의 모델 간의 차이점을 다시 한 번 살펴보겠습니다.
<?php

class NormalUser
{
    public $firstName = 'Alice';
}

$normalUser = new NormalUser;

$normalUser->firstName = 'Bob';

$normalUser->firstName; // Will return 'Bob'
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class LaravelUser extends Model
{
    protected $attributes = [
        'firstName' => 'Alice',
    ];
}

$laravelUser = new LaravelUser;

$laravelUser->firstName = 'Bob';

$laravelUser->firstName; // Will return 'Bob' as well
보시다시피 이 예에서 우리는 하나의 속성의 값Bob에 영향을 주려고 시도했다. 이 속성은 실제로는 클래스에 존재하지 않지만 속성$attributes에 존재한다.신기한 방법__set으로 이 정확한 행동을 실현해 봅시다.
<?php

class NormalUser
{
    public $attributes = [
        'firstName' => 'Alice',
    ];

    /**
     * The magic method __set receives the $name you want to affect the value on
     * and the value
     */
    public function __set($key, $value)
    {
        $this->attributes[$key] = $value;
    }
}

$normalUser = new NormalUser;

$normalUser->firstName = 'Bob';

/**
 * As we don't have the __get magic method define in this example for simplicity sake,
 * we will access the $attributes directly
 */
$normalUser->attributes['firstName']; // Will return 'Bob'
우리 시작했어!우리는 Laravel에서 __get__set 마술 방법의 기본적인 용법을 성공적으로 실현했다!코드 몇 줄만 있으면 돼!
이 신기한 방법들은 가능한 한 간단하고 세부적인 부분에 들어가지 않았다는 것을 기억하세요. 그것은 단지 그런 용례가 아니기 때문입니다. 만약에 당신이 그것이 어떻게 작동하는지 궁금하면 코드에 깊이 들어가 탐색을 하도록 초대합니다!(질문이 있으면 트위터에 연락 주세요)
마찬가지로, 만약 당신이 더 많은 것을 발굴하고 싶다면, 여기는 원본 코드의 링크입니다
laravel/framework
마지막까지 가는 것도 가장 재밌는 사례!🙌

__call()&__callStatic()

__call 호출 방법이 특정 클래스에서 발견되지 않았을 때 실행됩니다.Laravel에서 이런 신기한 방법은 매크로를 PHP에서 가능하게 한다.
나는 宏을 상세하게 소개하지는 않지만, 만약 당신이 흥미가 있다면, 당신의 Laravel 응용 프로그램에서 그것을 어떻게 사용하는지 설명하는 좋은 글이 있습니다👇
The Magic of Laravel Macros
일반 PHP에서 간단한 매크로 예를 재현하는 방법을 살펴보겠습니다.
<?php

class NormalUser
{
    public $firstName = 'Alice';

    public $lastName = 'Bob';
}

$normalUser = new NormalUser;

$normalUser->fullName(); // This will throw an error as no method "fullName" has been declared.
현재 __call 는 패키지 함수를 포함하는 그룹을 정의할 수 있으며, 프로그램에서 프로그래밍 방식으로 패키지 함수를 추가할 수 있습니다.
<?php

class NormalUser
{
    public $firstName = 'Alice';

    public $lastName = 'Bob';

    /**
     * We initialise our macros as an empty array that we will fill
     */
    public static $macros = [];

    /**
     * We define this method to add new macro as we go
     * the first argument will be the name of the macro we want to define
     * the second will be a Closure function that will be executed when calling the macro
     */
    public static function addMacro($name, $macro) {
        static::$macros[$name] = $macro;
    }

    /**
     * "__call" receives two parameters,
     * $name which will be the name of the function called in our case "fullName"
     * $arguments which will be all the arguments passed in the function in our case it'll just be an empty array as we can't pass any arguments in our function
     */
    public function __call(string $name, array $arguments) {
        /**
         * We retrieve the macro with the right name
         */
        $macro = static::$macros[$name];
        /**
         * Then we execute the macro with the arguments
         * Note: we need to bind the Closure with "$this" before calling it to allow the macro method to act in the same context
         */
        return call_user_func_array($macro->bindTo($this, static::class), $arguments);
    }
}

$normalUser = new NormalUser;

$normalUser->fullName(); // This will still break as we didn't define the macro "fullName" yet and the method "fullName" doesn't exist either

/**
 * We add the macro function "fullName"
 */
NormalUser::addMacro('fullName', function () {
    return $this->firstName.' '.$this->lastName;
});

$normalUser->fullName(); // Now, returns "Alice Bob"
宏은 이것보다 좀 복잡하지만, 마찬가지로 우리는 __call 마술 방법을 사용하여 간단한 宏 작업 버전을 만들었다.__callStatic의 작업 원리는 __call와 완전히 같지만 정적 방법에 적용된다.
마찬가지로, 당신이 더 발굴하고 싶다면, 여기는 Macroabletrait 소스 코드입니다
laravel/framework

마지막 타격


신사 숙녀 여러분, 처음 그것을 사용하기 시작했을 때, 라빌은 확실히 마력을 느꼈지만, 원본 코드 자체를 보면, 마력이 막후에서 어떻게 작동하는지 이해할 수 있습니다.
현실 생활의 마법처럼 해석 없이는 아무 일도 일어나지 않는다는 것은 코드에서 더욱 그렇다.항상 코드 한 줄이 어딘가에서 이 일을 하고 있으니, 너는 그것을 찾기만 하면 된다.
라빌에 대해 깊이 있게 알고 마법을 사라지게 해주고 트위터에 당신의 금괴를 공유하는 것을 잊지 마세요!
이 블로그는 최초로 발표되었으니 포옹해 주십시오🤗
특히 감사합니다:, my personal blog와...

좋은 웹페이지 즐겨찾기