使用神奇PHP的Getters和setter调用Laravel



我对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)。但我不知道如何将其应用于拉拉威尔。知道吗?

我为我的所有模型创建了一个名为"Moam"的父类(作为所有模型的母亲)在这个Moam中,我实现了那些被好的旧Zend框架所熟知的神奇方法。

/app/Models/Moam.php是:

<?php
namespace AppModels;
use Exception;
use IlluminateDatabaseEloquentModel;
use IlluminateSupportFacadesLog;
/* 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 AppModelsMoam;
...
class yourModelextends Moam{
   ...
}

最后,您可以按以下形式调用setter和getter:

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

例如:

$desc = $event->getDescription();
$event->setDescription("This is a blah blah blah...");

最新更新