本文介绍了Laravel中的自定义设置器和获取器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个棘手的问题.

我正在Laravel中构建一个框架,我希望我的对象以透明的方式与Rackspace交互.从现在开始,我无需考虑Rackspace即可上传/删除对象

I am building a framework in Laravel and I want my objects to interact with Rackspace in a transparent way. From now on I made it possible to upload/delete objects without having in mind Rackspace

$model->file = Input::file('thing'); // and it uploads to Rackspace.

我要实现的下一步是使用配置文件获取路由.行为类似于$route = $file->source(例如,源在数据库中带有hello.jpg的源代码),并获得$ route作为rackspace.com/WHATEVER/hello.jpg.我的配置文件中有rackspace.com/WHATEVER部分,因此,我唯一需要的就是如何使这种行为成为可能.

The next step I want to achieve is to get the route using my config file. The behaviour would be something like $route = $file->source (with source with hello.jpg in the database for instance) and get $route as rackspace.com/WHATEVER/hello.jpg. The part rackspace.com/WHATEVER is in my config file, so the only thing I need is how to make this behaviour.

我已经进行了广泛的搜索,但我只找到了__call()方法来进行搜索.我要像这样表现的字段是动态的,并且是通过数组设置的,例如:

I have been searching extensively and I only found the __call() method to do so. The fields I want to behave like this are dynamic and are setted from an array such as:

public static $rackspaceable = array('source' => 'images-demo');

其中images-demo是Rackspace容器.

Where images-demo is a Rackspace container.

有人知道要实现这一目标吗,甚至可能吗?

Does anyone knows to achieve that and if it is even possible?

推荐答案

这可能是您要寻找的:

class Model extends Eloquent {

    public static $rackspaceable = array('source' => 'images-demo');

    public function __get($key)
    {
        if (isset(static::$rackspaceable[$key]))
        {
            return static::$rackspaceable[$key];
        }

        return parent::__get($key);
    }

    public function __set($key, $value)
    {
        if (isset(static::$rackspaceable[$key]))
        {
            static::$rackspaceable[$key] = $value;
        }
        else
        {
            parent::__set($key, $value);
        }
    }
}

要使用它:

$model = new Model;

var_dump( $model->source );

$model->source = 'new value';

var_dump( $model->source );

这篇关于Laravel中的自定义设置器和获取器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 21:33