Merged branch master into translate-template

This commit is contained in:
Axel Pardemann
2016-09-23 11:44:18 -05:00
288 changed files with 9359 additions and 9024 deletions

View File

@@ -2,12 +2,9 @@
namespace DesignPatterns\More\Delegation;
/**
* Class JuniorDeveloper.
*/
class JuniorDeveloper
{
public function writeBadCode()
public function writeBadCode(): string
{
return 'Some junior developer generated code...';
}

View File

@@ -27,12 +27,6 @@ Code
You can also find these code on `GitHub`_
Usage.php
.. literalinclude:: Usage.php
:language: php
:linenos:
TeamLead.php
.. literalinclude:: TeamLead.php

View File

@@ -2,31 +2,23 @@
namespace DesignPatterns\More\Delegation;
/**
* Class TeamLead.
*/
class TeamLead
{
/** @var JuniorDeveloper */
protected $slave;
/**
* @var JuniorDeveloper
*/
private $junior;
/**
* Give junior developer into teamlead submission.
*
* @param JuniorDeveloper $junior
*/
public function __construct(JuniorDeveloper $junior)
{
$this->slave = $junior;
$this->junior = $junior;
}
/**
* TeamLead drink coffee, junior work.
*
* @return mixed
*/
public function writeCode()
public function writeCode(): string
{
return $this->slave->writeBadCode();
return $this->junior->writeBadCode();
}
}

View File

@@ -4,15 +4,13 @@ namespace DesignPatterns\More\Delegation\Tests;
use DesignPatterns\More\Delegation;
/**
* DelegationTest tests the delegation pattern.
*/
class DelegationTest extends \PHPUnit_Framework_TestCase
{
public function testHowTeamLeadWriteCode()
{
$junior = new Delegation\JuniorDeveloper();
$teamLead = new Delegation\TeamLead($junior);
$this->assertEquals($junior->writeBadCode(), $teamLead->writeCode());
}
}

View File

@@ -1,9 +0,0 @@
<?php
namespace DesignPatterns\More\Delegation;
// instantiate TeamLead and appoint to assistants JuniorDeveloper
$teamLead = new TeamLead(new JuniorDeveloper());
// team lead delegate write code to junior developer
echo $teamLead->writeCode();

View File

@@ -2,15 +2,10 @@
namespace DesignPatterns\More\EAV;
use SplObjectStorage;
/**
* Class Attribute.
*/
class Attribute implements ValueAccessInterface
class Attribute
{
/**
* @var SplObjectStorage
* @var \SplObjectStorage
*/
private $values;
@@ -19,64 +14,27 @@ class Attribute implements ValueAccessInterface
*/
private $name;
public function __construct()
public function __construct(string $name)
{
$this->values = new SplObjectStorage();
$this->values = new \SplObjectStorage();
$this->name = $name;
}
public function addValue(Value $value)
{
$this->values->attach($value);
}
/**
* @return SplObjectStorage
* @return \SplObjectStorage
*/
public function getValues()
public function getValues(): \SplObjectStorage
{
return $this->values;
}
/**
* @param ValueInterface $value
*
* @return $this
*/
public function addValue(ValueInterface $value)
{
if (!$this->values->contains($value)) {
$this->values->attach($value);
}
return $this;
}
/**
* @param ValueInterface $value
*
* @return $this
*/
public function removeValue(ValueInterface $value)
{
if ($this->values->contains($value)) {
$this->values->detach($value);
}
return $this;
}
/**
* @return string
*/
public function getName()
public function __toString(): string
{
return $this->name;
}
/**
* @param string $name
*
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
}

View File

@@ -2,15 +2,10 @@
namespace DesignPatterns\More\EAV;
use SplObjectStorage;
/**
* Class Entity.
*/
class Entity implements ValueAccessInterface
class Entity
{
/**
* @var SplObjectStorage
* @var \SplObjectStorage
*/
private $values;
@@ -19,64 +14,28 @@ class Entity implements ValueAccessInterface
*/
private $name;
public function __construct()
{
$this->values = new SplObjectStorage();
}
/**
* @return SplObjectStorage
*/
public function getValues()
{
return $this->values;
}
/**
* @param ValueInterface $value
*
* @return $this
*/
public function addValue(ValueInterface $value)
{
if (!$this->values->contains($value)) {
$this->values->attach($value);
}
return $this;
}
/**
* @param ValueInterface $value
*
* @return $this
*/
public function removeValue(ValueInterface $value)
{
if ($this->values->contains($value)) {
$this->values->detach($value);
}
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*
* @return $this
* @param Value[] $values
*/
public function setName($name)
public function __construct(string $name, $values)
{
$this->values = new \SplObjectStorage();
$this->name = $name;
return $this;
foreach ($values as $value) {
$this->values->attach($value);
}
}
public function __toString(): string
{
$text = [$this->name];
foreach ($this->values as $value) {
$text[] = (string) $value;
}
return join(', ', $text);
}
}

View File

@@ -11,81 +11,6 @@ where the number of attributes (properties, parameters) that can be used
to describe them is potentially vast, but the number that will actually apply
to a given entity is relatively modest.
Examples
--------
Check full work example in `example.php`_ file.
.. code-block:: php
use DesignPatterns\More\EAV\Entity;
use DesignPatterns\More\EAV\Attribute;
use DesignPatterns\More\EAV\Value;
// Create color attribute
$color = (new Attribute())->setName('Color');
// Create color values
$colorSilver = (new Value($color))->setName('Silver');
$colorGold = (new Value($color))->setName('Gold');
$colorSpaceGrey = (new Value($color))->setName('Space Grey');
// Create memory attribute
$memory = (new Attribute())->setName('Memory');
// Create memory values
$memory4Gb = (new Value($memory))->setName('4GB');
$memory8Gb = (new Value($memory))->setName('8GB');
$memory16Gb = (new Value($memory))->setName('16GB');
// Create storage attribute
$storage = (new Attribute())->setName('Storage');
// Create storage values
$storage128Gb = (new Value($storage))->setName('128GB');
$storage256Gb = (new Value($storage))->setName('256GB');
$storage512Gb = (new Value($storage))->setName('512GB');
$storage1Tb = (new Value($storage))->setName('1TB');
// Create entities with specific values
$mac = (new Entity())
->setName('MacBook')
// colors
->addValue($colorSilver)
->addValue($colorGold)
->addValue($colorSpaceGrey)
// memories
->addValue($memory8Gb)
// storages
->addValue($storage256Gb)
->addValue($storage512Gb)
;
$macAir = (new Entity())
->setName('MacBook Air')
// colors
->addValue($colorSilver)
// memories
->addValue($memory4Gb)
->addValue($memory8Gb)
// storages
->addValue($storage128Gb)
->addValue($storage256Gb)
->addValue($storage512Gb)
;
$macPro = (new Entity())
->setName('MacBook Pro')
// colors
->addValue($colorSilver)
// memories
->addValue($memory8Gb)
->addValue($memory16Gb)
// storages
->addValue($storage128Gb)
->addValue($storage256Gb)
->addValue($storage512Gb)
->addValue($storage1Tb)
;
UML Diagram
-----------
@@ -98,28 +23,32 @@ Code
You can also find these code on `GitHub`_
Entity.php
.. literalinclude:: Entity.php
:language: php
:linenos:
Attribute.php
.. literalinclude:: Attribute.php
:language: php
:linenos:
Value.php
.. literalinclude:: Value.php
:language: php
:linenos:
Test
----
Tests/EntityTest.php
Tests/EAVTest.php
.. literalinclude:: Tests/EntityTest.php
:language: php
:linenos:
Tests/AttributeTest.php
.. literalinclude:: Tests/AttributeTest.php
:language: php
:linenos:
Tests/ValueTest.php
.. literalinclude:: Tests/ValueTest.php
:language: php
:linenos:
.. _`example.php`: https://github.com/domnikl/DesignPatternsPHP/tree/master/More/EAV/example.php
.. _`GitHub`: https://github.com/domnikl/DesignPatternsPHP/tree/master/More/EAV
.. __: https://en.wikipedia.org/wiki/Entityattributevalue_model

View File

@@ -1,66 +0,0 @@
<?php
namespace DesignPatterns\More\EAV\Tests;
use DesignPatterns\More\EAV\Attribute;
use DesignPatterns\More\EAV\Value;
/**
* AttributeTest tests the Attribute model of EAV pattern.
*/
class AttributeTest extends \PHPUnit_Framework_TestCase
{
public function testCreationSuccess()
{
$attribute = new Attribute();
$this->assertInstanceOf('\DesignPatterns\More\EAV\Attribute', $attribute);
}
/**
* @depends testCreationSuccess
*/
public function testSetGetName()
{
$attribute = new Attribute();
$attribute->setName('Color');
$this->assertEquals('Color', $attribute->getName());
}
/**
* @depends testCreationSuccess
*/
public function testAddValue()
{
$attribute = new Attribute();
$attribute->setName('Color');
$colorSilver = new Value($attribute);
$colorSilver->setName('Silver');
$colorGold = new Value($attribute);
$colorGold->setName('Gold');
$this->assertTrue($attribute->getValues()->contains($colorSilver));
$this->assertTrue($attribute->getValues()->contains($colorGold));
}
/**
* @depends testAddValue
*/
public function testRemoveValue()
{
$attribute = new Attribute();
$attribute->setName('Color');
$colorSilver = new Value($attribute);
$colorSilver->setName('Silver');
$colorGold = new Value($attribute);
$colorGold->setName('Gold');
$attribute->removeValue($colorSilver);
$this->assertFalse($attribute->getValues()->contains($colorSilver));
$this->assertTrue($attribute->getValues()->contains($colorGold));
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace DesignPatterns\More\EAV\Tests;
use DesignPatterns\More\EAV\Attribute;
use DesignPatterns\More\EAV\Entity;
use DesignPatterns\More\EAV\Value;
class EAVTest extends \PHPUnit_Framework_TestCase
{
public function testCanAddAttributeToEntity()
{
$colorAttribute = new Attribute('color');
$colorSilver = new Value($colorAttribute, 'silver');
$colorBlack = new Value($colorAttribute, 'black');
$memoryAttribute = new Attribute('memory');
$memory8Gb = new Value($memoryAttribute, '8GB');
$entity = new Entity('MacBook Pro', [$colorSilver, $colorBlack, $memory8Gb]);
$this->assertEquals('MacBook Pro, color: silver, color: black, memory: 8GB', (string) $entity);
}
}

View File

@@ -1,145 +0,0 @@
<?php
namespace DesignPatterns\More\EAV\Tests;
use DesignPatterns\More\EAV\Attribute;
use DesignPatterns\More\EAV\Entity;
use DesignPatterns\More\EAV\Value;
/**
* EntityTest tests the Entity model of EAV pattern.
*/
class EntityTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider valueProvider
*
* @var string
*/
public function testSetGetName($name)
{
$macBook = new Entity();
$macBook->setName($name);
$this->assertEquals($name, $macBook->getName());
}
/**
* @dataProvider valueProvider
*
* @var string
* @var Value[] $values
*/
public function testAddValue($name, array $values)
{
$macBook = new Entity();
$macBook->setName($name);
foreach ($values as $value) {
$macBook->addValue($value);
$this->assertTrue($macBook->getValues()->contains($value));
}
$this->assertCount(count($values), $macBook->getValues());
}
/**
* @depends testAddValue
* @dataProvider valueProvider
*
* @var string
* @var Value[] $values
*/
public function testRemoveValue($name, array $values)
{
$macBook = new Entity();
$macBook->setName($name);
foreach ($values as $value) {
$macBook->addValue($value);
}
$macBook->removeValue($values[0]);
$this->assertFalse($macBook->getValues()->contains($values[0]));
unset($values[0]);
$this->assertCount(count($values), $macBook->getValues());
}
/**
* @return array
*/
public function valueProvider()
{
// color attribute
$color = new Attribute();
$color->setName('Color');
// color values
$colorSilver = new Value($color);
$colorSilver->setName('Silver');
$colorGold = new Value($color);
$colorGold->setName('Gold');
$colorSpaceGrey = new Value($color);
$colorSpaceGrey->setName('Space Grey');
// memory attribute
$memory = new Attribute();
$memory->setName('Memory');
// memory values
$memory4Gb = new Value($memory);
$memory4Gb->setName('4GB');
$memory8Gb = new Value($memory);
$memory8Gb->setName('8GB');
$memory16Gb = new Value($memory);
$memory16Gb->setName('16GB');
// storage attribute
$storage = new Attribute();
$storage->setName('Storage');
// storage values
$storage128Gb = new Value($storage);
$storage128Gb->setName('128GB');
$storage256Gb = new Value($storage);
$storage256Gb->setName('256GB');
$storage512Gb = new Value($storage);
$storage512Gb->setName('512GB');
$storage1Tb = new Value($storage);
$storage1Tb->setName('1TB');
return array(
array(
'MacBook',
array(
$colorSilver,
$colorGold,
$colorSpaceGrey,
$memory8Gb,
$storage256Gb,
$storage512Gb,
),
),
array(
'MacBook Air',
array(
$colorSilver,
$memory4Gb,
$memory8Gb,
$storage128Gb,
$storage256Gb,
$storage512Gb,
),
),
array(
'MacBook Pro',
array(
$colorSilver,
$memory8Gb,
$memory16Gb,
$storage128Gb,
$storage256Gb,
$storage512Gb,
$storage1Tb,
),
),
);
}
}

View File

@@ -1,46 +0,0 @@
<?php
namespace DesignPatterns\More\EAV\Tests;
use DesignPatterns\More\EAV\Attribute;
use DesignPatterns\More\EAV\Value;
/**
* ValueTest tests the Value model of EAV pattern.
*/
class ValueTest extends \PHPUnit_Framework_TestCase
{
public function testCreationSuccessWithAttribute()
{
$attribute = new Attribute();
$attribute->setName('Color');
$value = new Value($attribute);
$this->assertInstanceOf('\DesignPatterns\More\EAV\Value', $value);
}
public function testSetGetName()
{
$attribute = new Attribute();
$attribute->setName('Color');
$value = new Value($attribute);
$value->setName('Silver');
$this->assertEquals('Silver', $value->getName());
}
public function testSetGetAttribute()
{
$attribute = new Attribute();
$attribute->setName('Color');
$value = new Value($attribute);
$value->setName('Silver');
$this->assertSame($attribute, $value->getAttribute());
$value->setAttribute($attribute);
$this->assertSame($attribute, $value->getAttribute());
}
}

View File

@@ -2,10 +2,7 @@
namespace DesignPatterns\More\EAV;
/**
* Class Value.
*/
class Value implements ValueInterface
class Value
{
/**
* @var Attribute
@@ -17,53 +14,16 @@ class Value implements ValueInterface
*/
private $name;
/**
* @param Attribute $attribute
*/
public function __construct(Attribute $attribute)
{
$this->setAttribute($attribute);
}
/**
* @param Attribute $attribute
*
* @return $this
*/
public function setAttribute(Attribute $attribute)
{
$this->attribute && $this->attribute->removeValue($this); // Remove value from current attribute
$attribute->addValue($this); // Add value to new attribute
$this->attribute = $attribute;
return $this;
}
/**
* @return Attribute
*/
public function getAttribute()
{
return $this->attribute;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*
* @return $this
*/
public function setName($name)
public function __construct(Attribute $attribute, string $name)
{
$this->name = $name;
$this->attribute = $attribute;
return $this;
$attribute->addValue($this);
}
public function __toString(): string
{
return sprintf('%s: %s', $this->attribute, $this->name);
}
}

View File

@@ -1,24 +0,0 @@
<?php
namespace DesignPatterns\More\EAV;
/**
* Interface ValueAccessInterface.
*/
interface ValueAccessInterface
{
/**
* @return \SplObjectStorage
*/
public function getValues();
/**
* @param ValueInterface $value
*/
public function addValue(ValueInterface $value);
/**
* @param ValueInterface $value
*/
public function removeValue(ValueInterface $value);
}

View File

@@ -1,24 +0,0 @@
<?php
namespace DesignPatterns\More\EAV;
/**
* Interface ValueInterface.
*/
interface ValueInterface
{
/**
* @param Attribute $attribute
*/
public function __construct(Attribute $attribute);
/**
* @param Attribute $attribute
*/
public function setAttribute(Attribute $attribute);
/**
* @return Attribute
*/
public function getAttribute();
}

View File

@@ -1,67 +0,0 @@
<?php
require '../../vendor/autoload.php';
use DesignPatterns\More\EAV\Attribute;
use DesignPatterns\More\EAV\Entity;
use DesignPatterns\More\EAV\Value;
// Create color attribute
$color = (new Attribute())->setName('Color');
// Create color values
$colorSilver = (new Value($color))->setName('Silver');
$colorGold = (new Value($color))->setName('Gold');
$colorSpaceGrey = (new Value($color))->setName('Space Grey');
// Create memory attribute
$memory = (new Attribute())->setName('Memory');
// Create memory values
$memory4Gb = (new Value($memory))->setName('4GB');
$memory8Gb = (new Value($memory))->setName('8GB');
$memory16Gb = (new Value($memory))->setName('16GB');
// Create storage attribute
$storage = (new Attribute())->setName('Storage');
// Create storage values
$storage128Gb = (new Value($storage))->setName('128GB');
$storage256Gb = (new Value($storage))->setName('256GB');
$storage512Gb = (new Value($storage))->setName('512GB');
$storage1Tb = (new Value($storage))->setName('1TB');
// Create entities with specific values
$mac = (new Entity())
->setName('MacBook')
// colors
->addValue($colorSilver)
->addValue($colorGold)
->addValue($colorSpaceGrey)
// memories
->addValue($memory8Gb)
// storages
->addValue($storage256Gb)
->addValue($storage512Gb);
$macAir = (new Entity())
->setName('MacBook Air')
// colors
->addValue($colorSilver)
// memories
->addValue($memory4Gb)
->addValue($memory8Gb)
// storages
->addValue($storage128Gb)
->addValue($storage256Gb)
->addValue($storage512Gb);
$macPro = (new Entity())
->setName('MacBook Pro')
// colors
->addValue($colorSilver)
// memories
->addValue($memory8Gb)
->addValue($memory16Gb)
// storages
->addValue($storage128Gb)
->addValue($storage256Gb)
->addValue($storage512Gb)
->addValue($storage1Tb);

View File

@@ -2,50 +2,43 @@
namespace DesignPatterns\More\Repository;
/**
* Class MemoryStorage.
*/
class MemoryStorage implements Storage
class MemoryStorage
{
private $data;
private $lastId;
public function __construct()
{
$this->data = array();
$this->lastId = 0;
}
/**
* @var array
*/
private $data = [];
/**
* {@inheritdoc}
* @var int
*/
public function persist($data)
private $lastId = 0;
public function persist(array $data): int
{
$this->data[++$this->lastId] = $data;
$this->lastId++;
$data['id'] = $this->lastId;
$this->data[$this->lastId] = $data;
return $this->lastId;
}
/**
* {@inheritdoc}
*/
public function retrieve($id)
{
return isset($this->data[$id]) ? $this->data[$id] : null;
}
/**
* {@inheritdoc}
*/
public function delete($id)
public function retrieve(int $id): array
{
if (!isset($this->data[$id])) {
return false;
throw new \OutOfRangeException(sprintf('No data found for ID %d', $id));
}
$this->data[$id] = null;
unset($this->data[$id]);
return $this->data[$id];
}
return true;
public function delete(int $id)
{
if (!isset($this->data[$id])) {
throw new \OutOfRangeException(sprintf('No data found for ID %d', $id));
}
unset($this->data[$id]);
}
}

View File

@@ -2,15 +2,10 @@
namespace DesignPatterns\More\Repository;
/**
* Post represents entity for some post that user left on the site.
*
* Class Post
*/
class Post
{
/**
* @var int
* @var int|null
*/
private $id;
@@ -24,92 +19,43 @@ class Post
*/
private $text;
/**
* @var string
*/
private $author;
public static function fromState(array $state): Post
{
return new self(
$state['id'],
$state['title'],
$state['text']
);
}
/**
* @var \DateTime
* @param int|null $id
* @param string $text
* @param string $title
*/
private $created;
public function __construct($id, string $title, string $text)
{
$this->id = $id;
$this->text = $text;
$this->title = $title;
}
/**
* @param int $id
*/
public function setId($id)
public function setId(int $id)
{
$this->id = $id;
}
/**
* @return int
*/
public function getId()
public function getId(): int
{
return $this->id;
}
/**
* @param string $author
*/
public function setAuthor($author)
{
$this->author = $author;
}
/**
* @return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* @param \DateTime $created
*/
public function setCreated($created)
{
$this->created = $created;
}
/**
* @return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* @param string $text
*/
public function setText($text)
{
$this->text = $text;
}
/**
* @return string
*/
public function getText()
public function getText(): string
{
return $this->text;
}
/**
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return string
*/
public function getTitle()
public function getTitle(): string
{
return $this->title;
}

View File

@@ -3,80 +3,44 @@
namespace DesignPatterns\More\Repository;
/**
* Repository for class Post
* This class is between Entity layer(class Post) and access object layer(interface Storage).
* This class is situated between Entity layer (class Post) and access object layer (MemoryStorage).
*
* Repository encapsulates the set of objects persisted in a data store and the operations performed over them
* providing a more object-oriented view of the persistence layer
*
* Repository also supports the objective of achieving a clean separation and one-way dependency
* between the domain and data mapping layers
*
* Class PostRepository
*/
class PostRepository
{
/**
* @var MemoryStorage
*/
private $persistence;
public function __construct(Storage $persistence)
public function __construct(MemoryStorage $persistence)
{
$this->persistence = $persistence;
}
/**
* Returns Post object by specified id.
*
* @param int $id
*
* @return Post|null
*/
public function getById($id)
public function findById(int $id): Post
{
$arrayData = $this->persistence->retrieve($id);
if (is_null($arrayData)) {
return;
throw new \InvalidArgumentException(sprintf('Post with ID %d does not exist'));
}
$post = new Post();
$post->setId($arrayData['id']);
$post->setAuthor($arrayData['author']);
$post->setCreated($arrayData['created']);
$post->setText($arrayData['text']);
$post->setTitle($arrayData['title']);
return $post;
return Post::fromState($arrayData);
}
/**
* Save post object and populate it with id.
*
* @param Post $post
*
* @return Post
*/
public function save(Post $post)
{
$id = $this->persistence->persist(array(
'author' => $post->getAuthor(),
'created' => $post->getCreated(),
$id = $this->persistence->persist([
'text' => $post->getText(),
'title' => $post->getTitle(),
));
]);
$post->setId($id);
return $post;
}
/**
* Deletes specified Post object.
*
* @param Post $post
*
* @return bool
*/
public function delete(Post $post)
{
return $this->persistence->delete($post->getId());
}
}

View File

@@ -43,12 +43,6 @@ PostRepository.php
:language: php
:linenos:
Storage.php
.. literalinclude:: Storage.php
:language: php
:linenos:
MemoryStorage.php
.. literalinclude:: MemoryStorage.php
@@ -58,4 +52,10 @@ MemoryStorage.php
Test
----
Tests/RepositoryTest.php
.. literalinclude:: Tests/RepositoryTest.php
:language: php
:linenos:
.. _`GitHub`: https://github.com/domnikl/DesignPatternsPHP/tree/master/More/Repository

View File

@@ -1,42 +0,0 @@
<?php
namespace DesignPatterns\More\Repository;
/**
* Interface Storage.
*
* This interface describes methods for accessing storage.
* Concrete realization could be whatever we want - in memory, relational database, NoSQL database and etc
*/
interface Storage
{
/**
* Method to persist data
* Returns new id for just persisted data.
*
* @param array() $data
*
* @return int
*/
public function persist($data);
/**
* Returns data by specified id.
* If there is no such data null is returned.
*
* @param int $id
*
* @return array|null
*/
public function retrieve($id);
/**
* Delete data specified by id
* If there is no such data - false returns, if data has been successfully deleted - true returns.
*
* @param int $id
*
* @return bool
*/
public function delete($id);
}

View File

@@ -0,0 +1,21 @@
<?php
namespace DesignPatterns\More\Repository\Tests;
use DesignPatterns\More\Repository\MemoryStorage;
use DesignPatterns\More\Repository\Post;
use DesignPatterns\More\Repository\PostRepository;
class Repository extends \PHPUnit_Framework_TestCase
{
public function testCanPersistAndFindPost()
{
$repository = new PostRepository(new MemoryStorage());
$post = new Post(null, 'Repository Pattern', 'Design Patterns PHP');
$repository->save($post);
$this->assertEquals(1, $post->getId());
$this->assertEquals($post->getId(), $repository->findById(1)->getId());
}
}

View File

@@ -1,7 +0,0 @@
<?php
namespace DesignPatterns\More\ServiceLocator;
class DatabaseService implements DatabaseServiceInterface
{
}

View File

@@ -1,7 +0,0 @@
<?php
namespace DesignPatterns\More\ServiceLocator;
interface DatabaseServiceInterface
{
}

View File

@@ -2,6 +2,6 @@
namespace DesignPatterns\More\ServiceLocator;
class LogService implements LogServiceInterface
class LogService
{
}

View File

@@ -1,7 +0,0 @@
<?php
namespace DesignPatterns\More\ServiceLocator;
interface LogServiceInterface
{
}

View File

@@ -35,42 +35,18 @@ Code
You can also find these code on `GitHub`_
ServiceLocatorInterface.php
.. literalinclude:: ServiceLocatorInterface.php
:language: php
:linenos:
ServiceLocator.php
.. literalinclude:: ServiceLocator.php
:language: php
:linenos:
LogServiceInterface.php
.. literalinclude:: LogServiceInterface.php
:language: php
:linenos:
LogService.php
.. literalinclude:: LogService.php
:language: php
:linenos:
DatabaseServiceInterface.php
.. literalinclude:: DatabaseServiceInterface.php
:language: php
:linenos:
DatabaseService.php
.. literalinclude:: DatabaseService.php
:language: php
:linenos:
Test
----

View File

@@ -2,104 +2,87 @@
namespace DesignPatterns\More\ServiceLocator;
class ServiceLocator implements ServiceLocatorInterface
class ServiceLocator
{
/**
* All services.
*
* @var array
*/
private $services;
private $services = [];
/**
* The services which have an instance.
*
* @var array
*/
private $instantiated;
private $instantiated = [];
/**
* True if a service can be shared.
*
* @var array
*/
private $shared;
private $shared = [];
public function __construct()
/**
* instead of supplying a class here, you could also store a service for an interface
*
* @param string $class
* @param object $service
* @param bool $share
*/
public function addInstance(string $class, $service, bool $share = true)
{
$this->services = array();
$this->instantiated = array();
$this->shared = array();
$this->services[$class] = $service;
$this->instantiated[$class] = $service;
$this->shared[$class] = $share;
}
/**
* Registers a service with specific interface.
* instead of supplying a class here, you could also store a service for an interface
*
* @param string $interface
* @param string|object $service
* @param bool $share
* @param string $class
* @param array $params
* @param bool $share
*/
public function add($interface, $service, $share = true)
public function addClass(string $class, array $params, bool $share = true)
{
/*
* When you add a service, you should register it
* with its interface or with a string that you can use
* in the future even if you will change the service implementation.
*/
if (is_object($service) && $share) {
$this->instantiated[$interface] = $service;
}
$this->services[$interface] = (is_object($service) ? get_class($service) : $service);
$this->shared[$interface] = $share;
$this->services[$class] = $params;
$this->shared[$class] = $share;
}
/**
* Checks if a service is registered.
*
* @param string $interface
*
* @return bool
*/
public function has($interface)
public function has(string $interface): bool
{
return isset($this->services[$interface]) || isset($this->instantiated[$interface]);
}
/**
* Gets the service registered for the interface.
* @param string $class
*
* @param string $interface
*
* @return mixed
* @return object
*/
public function get($interface)
public function get(string $class)
{
// Retrieves the instance if it exists and it is shared
if (isset($this->instantiated[$interface]) && $this->shared[$interface]) {
return $this->instantiated[$interface];
if (isset($this->instantiated[$class]) && $this->shared[$class]) {
return $this->instantiated[$class];
}
// otherwise gets the service registered.
$service = $this->services[$interface];
$args = $this->services[$class];
// You should check if the service class exists and
// the class is instantiable.
switch (count($args)) {
case 0:
$object = new $class();
break;
case 1:
$object = new $class($args[0]);
break;
case 2:
$object = new $class($args[0], $args[1]);
break;
case 3:
$object = new $class($args[0], $args[1], $args[2]);
break;
default:
throw new \OutOfRangeException('Too many arguments given');
}
// This example is a simple implementation, but
// when you create a service, you can decide
// if $service is a factory or a class.
// By registering a factory you can create your services
// using the DependencyInjection pattern.
// ...
// Creates the service object
$object = new $service();
// and saves it if the service must be shared.
if ($this->shared[$interface]) {
$this->instantiated[$interface] = $object;
if ($this->shared[$class]) {
$this->instantiated[$class] = $object;
}
return $object;

View File

@@ -1,24 +0,0 @@
<?php
namespace DesignPatterns\More\ServiceLocator;
interface ServiceLocatorInterface
{
/**
* Checks if a service is registered.
*
* @param string $interface
*
* @return bool
*/
public function has($interface);
/**
* Gets the service registered for the interface.
*
* @param string $interface
*
* @return mixed
*/
public function get($interface);
}

View File

@@ -2,23 +2,12 @@
namespace DesignPatterns\More\ServiceLocator\Tests;
use DesignPatterns\More\ServiceLocator\DatabaseService;
use DesignPatterns\More\ServiceLocator\LogService;
use DesignPatterns\More\ServiceLocator\ServiceLocator;
use PHPUnit_Framework_TestCase as TestCase;
class ServiceLocatorTest extends TestCase
{
/**
* @var LogService
*/
private $logService;
/**
* @var DatabaseService
*/
private $databaseService;
/**
* @var ServiceLocator
*/
@@ -27,116 +16,21 @@ class ServiceLocatorTest extends TestCase
public function setUp()
{
$this->serviceLocator = new ServiceLocator();
$this->logService = new LogService();
$this->databaseService = new DatabaseService();
}
public function testHasServices()
{
$this->serviceLocator->add(
'DesignPatterns\More\ServiceLocator\LogServiceInterface',
$this->logService
);
$this->serviceLocator->addInstance(LogService::class, new LogService());
$this->serviceLocator->add(
'DesignPatterns\More\ServiceLocator\DatabaseServiceInterface',
$this->databaseService
);
$this->assertTrue($this->serviceLocator->has('DesignPatterns\More\ServiceLocator\LogServiceInterface'));
$this->assertTrue($this->serviceLocator->has('DesignPatterns\More\ServiceLocator\DatabaseServiceInterface'));
$this->assertFalse($this->serviceLocator->has('DesignPatterns\More\ServiceLocator\FakeServiceInterface'));
$this->assertTrue($this->serviceLocator->has(LogService::class));
$this->assertFalse($this->serviceLocator->has(self::class));
}
public function testServicesWithObject()
public function testGetWillInstantiateLogServiceIfNoInstanceHasBeenCreatedYet()
{
$this->serviceLocator->add(
'DesignPatterns\More\ServiceLocator\LogServiceInterface',
$this->logService
);
$this->serviceLocator->addClass(LogService::class, []);
$logger = $this->serviceLocator->get(LogService::class);
$this->serviceLocator->add(
'DesignPatterns\More\ServiceLocator\DatabaseServiceInterface',
$this->databaseService
);
$this->assertSame(
$this->logService,
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\LogServiceInterface')
);
$this->assertSame(
$this->databaseService,
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\DatabaseServiceInterface')
);
}
public function testServicesWithClass()
{
$this->serviceLocator->add(
'DesignPatterns\More\ServiceLocator\LogServiceInterface',
get_class($this->logService)
);
$this->serviceLocator->add(
'DesignPatterns\More\ServiceLocator\DatabaseServiceInterface',
get_class($this->databaseService)
);
$this->assertNotSame(
$this->logService,
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\LogServiceInterface')
);
$this->assertInstanceOf(
'DesignPatterns\More\ServiceLocator\LogServiceInterface',
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\LogServiceInterface')
);
$this->assertNotSame(
$this->databaseService,
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\DatabaseServiceInterface')
);
$this->assertInstanceOf(
'DesignPatterns\More\ServiceLocator\DatabaseServiceInterface',
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\DatabaseServiceInterface')
);
}
public function testServicesNotShared()
{
$this->serviceLocator->add(
'DesignPatterns\More\ServiceLocator\LogServiceInterface',
$this->logService,
false
);
$this->serviceLocator->add(
'DesignPatterns\More\ServiceLocator\DatabaseServiceInterface',
$this->databaseService,
false
);
$this->assertNotSame(
$this->logService,
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\LogServiceInterface')
);
$this->assertInstanceOf(
'DesignPatterns\More\ServiceLocator\LogServiceInterface',
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\LogServiceInterface')
);
$this->assertNotSame(
$this->databaseService,
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\DatabaseServiceInterface')
);
$this->assertInstanceOf(
'DesignPatterns\More\ServiceLocator\DatabaseServiceInterface',
$this->serviceLocator->get('DesignPatterns\More\ServiceLocator\DatabaseServiceInterface')
);
$this->assertInstanceOf('DesignPatterns\More\ServiceLocator\LogService', $logger);
}
}