简体   繁体   English

Laravel中的自定义设置器和获取器

[英]Custom setters and getters in Laravel

Here's a tricky question. 这是一个棘手的问题。

I am building a framework in Laravel and I want my objects to interact with Rackspace in a transparent way. 我正在Laravel中构建一个框架,我希望我的对象以透明的方式与Rackspace交互。 From now on I made it possible to upload/delete objects without having in mind Rackspace 从现在开始,我无需考虑Rackspace就可以上传/删除对象

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

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. 行为将类似于$route = $file->source (例如,源在数据库中带有hello.jpg的源),并将$ route命名为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. 我的配置文件中有一部分rackspace.com/WHATEVER,所以我唯一需要做的就是如何做到这一点。

I have been searching extensively and I only found the __call() method to do so. 我已经进行了广泛的搜索,而我只发现了__call()方法。 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');

Where images-demo is a Rackspace container. 其中images-demo是Rackspace容器。

Does anyone knows to achieve that and if it is even possible? 有谁知道实现这一目标,甚至有可能实现吗?

This might be what you are looking for: 这可能是您要寻找的:

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);
        }
    }
}

To use it: 要使用它:

$model = new Model;

var_dump( $model->source );

$model->source = 'new value';

var_dump( $model->source );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM