greenkin/magic

Support trait for standard plain classes that encapsulate private or protected fields through getters/setters

Installs: 3

Dependents: 0

Stars: 2

Watchers: 1

Language: PHP

1.0.5 2014-06-13 12:46 UTC

README

Build Status

Support trait for standard plain classes that encapsulate private or protected fields through getters/setters.

This is especially useful for ORM models (e.g: Doctrine).

Usage

Using Composer:

"require": {
    "greenkin/magic": "1.0.*"
}

Requirement

  • PHP 5.4+

Example

Let's take this plain old PHP class.

<?php

class MyEntity
{
    use Magic;

    private $name;

    private $active;

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function isActive()
    {
        return $this->active;
    }

    public function setActive($active)
    {
        $this->active = $active;
    }
}

Manipulating this class would normally require the use of those getters and setters methods.

<?php

$entity = new MyEntity;
$entity->setName('plop');
$entity->setActive(true);

$name = $entity->getName();

With magic:

<?php

// This will instantiate the object and dynamically use setters
// to fill properties given by the array
$entity = MyEntity::make(['name' => 'plop', 'active' => true]);

// Will dynamically call $entity->getName()
$name = $entity->name;

// Will call $entity->isActive();
$active = $entity->active; 

// Will dynamically call $entity->setName('bop')
$entity->name = 'bop'; 

// Updates all fields using their respective setters
$entity->set(['name' => 'foo', 'active' => 'false']);

Licence

MIT