使用对象作为键的多维地图

时间:2018-09-04 11:36:21

标签: php collections set factory splobjectstorage

我有一组对象(MainObject),它们由两个对象(SubObject1SubObject2)和一个字符串(theString)唯一地定义。我通过从基于两个子对象的现有对象和字符串(如果存在的话)中返回一个现有对象,从集合中检索MainObject,否则创建一个新对象,将其添加到集合中,然后返回该对象。

下面的伪代码在使标准数组可以将对象用作键的make国中证明了这一点。

class SubObject1{}
class SubObject2{}
class MainObject{
    private $subObject1, $subObject2, $theString;
    public function __construct(SubObject1 $subObject1, SubObject2 $subObject2, string $theString):MainObject {
        $this->subObject1=$subObject1;
        $this->subObject2=$subObject2;
        $this->theString=$theString;
    }
}

class ObjectCollection
{
    private $map=[];
    public function getObject(SubObject1 $subObject1, SubObject2 $subObject2, string $theString):MainObject {
        if(isset($this->map[$subObject1][$subObject2][$theString])) {
            $mainObject=$this->map[$subObject1][$subObject2][$theString];
        }
        else {
            $mainObject=new MainObject($subObject1, $subObject2, $theString);
            $this->map[$subObject1][$subObject2][$theString]=$mainObject;
        }
        return $mainObject;
    }
}

$objectCollection=new ObjectCollection();
$subObject1_1=new SubObject1();
$subObject1_2=new SubObject1();
$subObject2_1=new SubObject2();
$subObject2_1=new SubObject2();

$o=$objectCollection->getObject($subObject1_1, $subObject2_1, 'hello');    //returns a new object
$o=$objectCollection->getObject($subObject1_2, $subObject2_1, 'hello');    //returns a new object
$o=$objectCollection->getObject($subObject1_1, $subObject2_1, 'goodby');   //returns a new object

$o=$objectCollection->getObject($subObject1_1, $subObject2_1, 'hello');    //returns existing object

应如何最好地实施?

一种可能性是类似于以下未经测试的代码,但是它有点冗长,并且对是否有更干净的解决方案很感兴趣。

public function getObject(SubObject1 $subObject1, SubObject2 $subObject2, string $theString):MainObject {
    if(isset($this->map[$theString])) {
        if($this->map[$theString]->contains($subObject1)) {
            $subObject1Storage=$this->map[$theString][$subObject1];
            if($subObject1Storage->contains($subObject2)) {
                $mainObject=$subObject1Storage[$subObject2];
            }
            else {
                $mainObject=new MainObject($subObject1, $subObject2, $theString);
                $subObject1Storage[$subObject2]=$mainObject;
            }

        }
        else {
            $subObject1Storage = new \SplObjectStorage();
            $this->map[$theString][$subObject1]=$subObject1Storage;
            $mainObject=new MainObject($subObject1, $subObject2, $theString);
            $subObject1Storage[$subObject2]=$mainObject;
        }
    }
    else {
        $this->map[$theString] = new \SplObjectStorage();
        $subObject1Storage = new \SplObjectStorage();
        $this->map[$theString][$subObject1]=$subObject1Storage;
        $mainObject=new MainObject($subObject1, $subObject2, $theString);
        $subObject1Storage[$subObject2]=$mainObject;
    }
    return $mainObject;
}

1 个答案:

答案 0 :(得分:0)

我想到的逻辑如下:

工厂(如果对象太多,则为抽象工厂)将负责创建对象本身。

容器将映射唯一标识符与工厂创建的对象。 并可以根据这些标识符检索对象。

那是简单的部分,自定义部分应该更简单,您可以添加自己的方法来使用别名等来完成所需的魔术。

namespace Example;

/**
* Class ObjectFactory
*
* @package Example
*/
class ObjectFactory {

/**
 * This is obviosuly not ideal but it can work
 * with a limited amount of objects. Otherwise use an
 * abstract factory and let each instance take care of a few
 * related objects
 *
 * @param string $objectAlias
 *
 * @throws \Exception
 */
public function make(string $objectAlias) {
  switch($objectAlias) {
    case 'object_unique_id_1':
      try{
        $instance = new $objectAlias;
      }catch (\Exception $exception) {
        // log or whatever and rethrow
        throw new \Exception("Invalid class? maybe, I dunno");
      }
    // return $instance
    // etc
  }
}
}

您还可以在此处使用Reflection来递归获取对象的参数,并根据构造中的参数将对象的新实例转储到当前对象中,从而基本创建自己的小DI容器。

但是,如果您想保持理智,请使用Pimple之类的东西。


容器:

<?php

namespace Example;

/**
 * Class Container
 *
 * @package Example
 */
class Container {

  /**
   * @var array
   */
  private $map = [];

  /**
   * @param $objectAlias
   * @param $objectInstance
   *
   * @throws \Exception
   */
  public function set($objectAlias, $objectInstance) {
    // You can use a try catch here, I chose not to
    if(isset($this->map[$objectAlias])) {
      throw new \Exception("Already exists");
    }
    $this->map[$objectAlias] = $objectInstance;
  }

  /**
   * @param $objectAlias
   *
   * @return bool|mixed
   */
  public function get($objectAlias) {
    if(isset($this->map[$objectAlias])) {
      return $this->map[$objectAlias];
    }
    return false;
  }
}

将保存您自己的方法的特定容器

<?php

namespace Example;

/**
 * Class ContainerHashMapThingy
 *
 * @package Example
 */
class ContainerHashMapThingy extends Container {
    // Your methods go here
}

还有一个示例对象:

<?php

namespace Example;

/**
 * Class ExampleObject1
 *
 * @package Example
 */
class ExampleObject1 {

  /**
   * @return string
   */
  public function alias() {
    // This is just for example sake
    // You can just as well have a config, another class to map them or not map them at all
    return 'example_object_1';
  }
}

一个实际的例子

<?php

$factory = new \Example\ObjectFactory();
$container = new \Example\Container();

$objectOne = $factory->make('example_object_1');
$container->set('first_object', $objectOne);

这里的想法是给您一个干净的容器+工厂的清单。

如果扩展容器,则可以实现自己的方法,可以从map数组中删除内容,甚至可以重写set方法来满足自己的需求。


虽然这不是一个完整的答案,但是很难给出答案,因为正如我所说,您的需求可能会有所不同。

我希望这能使您走上正确的轨道。