Search code examples
phpframeworkslaravellaravel-4call

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. 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.

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.

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

Where images-demo is a Rackspace container.

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


Solution

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