魔术PHP的Getters和setter叫Laravel

时间:2014-09-01 09:46:18

标签: php laravel laravel-4 magic-function

我对PHP魔术方法并不熟悉,而且我正在尝试创建与Laravel框架交互的隐式getter和setter。现在,我知道有访问器和增变器,但必须明确声明它们。我想要的是使用某种隐式函数而不是声明它们。 我在Zend框架中看到过这个,就像

public function __call ($method, $params) {

    $property = strtolower($this->_getCamelCaseToUnderscoreFilter()->filter(substr($method, 3)));

    if (!property_exists($this, $property))
        return null;
    // Getters
    elseif (substr($method, 0, 3) == 'get')
    {
        return $this->$property;
    }
    // Setters
    elseif (substr($method, 0, 3) == 'set')
    {
        $this->$property = $params[0];
        return $this;
    }
    else
        return null;
}

现在,如果我有一个具有此功能的模型,我将只能$model->getProperty()$model->setProperty($property)。 但我不确定如何将它应用于Laravel。任何想法?

1 个答案:

答案 0 :(得分:0)

我为所有名为“ Moam”的模型创建了一个父类(作为所有模型的母亲) 在此Moam中,我实现了旧的Zend框架众所周知的魔术方法。

/app/Models/Moam.php是:

request.get('http://example.com/img.png').pipe(request.put(signedRequest));

在其他模型中,您必须这样声明模型:

<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

/* Mother of all models*/
class Moam extends Model
{   
    /* Implementation of magical get and set method for manipulation model properties
     * i.e. setFirstName('xxx') sets property first_name to 'xxx'
     *      getFirstName() returns value of property first_name
     *
     * So Capitals replaced underscores (_) in property name
     */

    public function __call($methodName, $args) {
        if (preg_match('~^(set|get)([A-Z])(.*)$~', $methodName, $matches)) {

            $split = preg_split('/(?=[A-Z])/',$methodName);
            $property = strtolower (implode("_",array_slice($split,1)));

            $attributes = $this->getAttributes();
            if (!array_key_exists($property,$attributes)){
                Log::error(get_class($this) . ' has no attribute named "' . $property . '"');
                throw new Exception(get_class($this) . ' has no attribute named "' . $property . '"');
            } else {

                switch($matches[1]) {
                case 'set':
                    return $this->setAttribute($property, $args[0]);
                case 'get':
                    return ($attributes[$property]);
                }
            }
        }

        return parent::__call($methodName, $args);
    }
}

最后,您可以通过以下形式调用设置方法和获取方法:

use App\Models\Moam;
...

class yourModelextends Moam{
   ...
}

例如:

$modelVariable->getAPropertyName();
$modelVariable->setAPropertyName(propertyValue);