【问题标题】:What is the best practice in PHP to create multiple objects if you know only their interface如果您只知道它们的接口,那么在 PHP 中创建多个对象的最佳实践是什么
【发布时间】:2015-12-30 23:00:44
【问题描述】:

我有一个类来操作具有定义接口的对象

class TaskManager
{
    /**
     * @param TaskInterface $task
     * @param string $command
     * @return TaskInterface
     */
    public static function editTask($task, $command)
    {
        $task->setStatus(TaskInterface::TASK_STATUS_ACTIVE);
        $task->setCommand($command);   
        $task->taskSave();
        return $task;
    }
}

我可以通过将其实例作为方法参数传递来创建单个对象。这很简单。但是我应该如何创建它们呢?

public static function export()
{
    $commands = self::getCommandsToAdd();
    foreach($commands as $c){
        //This is wrong.
        $task = new TaskInterface();
        $task->setCommand($c);
        $task->save();
        //don't need to return it if it's saved
    }
}

我无法以这种方式创建它。传递新对象数组显然是个坏主意。另一种方法是将类名作为字符串传递并调用其方法来检索新对象。但这似乎也是错误的

【问题讨论】:

  • 应该 (public status function export()) 是 static 还是 status
  • 是的,它是静态的,抱歉

标签: php oop interface


【解决方案1】:

我想我自己想出了一个解决方案。可以使用工厂接口来传递工厂对象。

interface TaskFactoryInterface
{
     public static function createNew();
}

/**
 * @param TaskFactoryInterface $task_factory
 */
public static function export($task_factory)
{
    $commands = self::getCommandsToAdd();
    foreach($commands as $c){
        $task = $task_factory::createNew();
        $task->setCommand($c);
        $task->save();
        //don't need to return it if it's saved
    }
}

你怎么看?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 2010-09-17
    • 2010-10-14
    • 2012-12-13
    相关资源
    最近更新 更多