改编类使用php的__call方法:传递参数

时间:2018-10-06 07:52:05

标签: php doctrine-orm symfony-3.4

基于我的Symfony 3.4项目中的answer,我想到了使用神奇的__call方法以具有一种通用的方式来调用存储库即服务:

namespace AppBundle\Services;

use Doctrine\ORM\EntityManagerInterface;

class RepositoryServiceAdapter
{
        private $repository=null;

        /**
        * @param EntityManagerInterface the Doctrine entity Manager
        * @param String $entityName The name of the entity that we will retrieve the repository
        */
        public function __construct(EntityManagerInterface $entityManager,$entityName)
        {
            $this->repository=$entityManager->getRepository($entityName)
        }

        public function __call($name,$arguments)
        {     
          if(empty($arguments)){ //No arguments has been passed
             $this->repository->$name();
          } else {
             //@todo: figure out how to pass the parameters
             $this->repository->$name();
          }
        }
}

但是我陷入了这个问题:

存储库方法将具有以下形式:

public function aMethod($param1,$param2)
{
  //Some magic is done here
}

因此,如果我确切知道将调用哪种方法,我将需要某种方式迭代数组$arguments以便将参数传递给函数,例如,如果我知道某个方法,则可以任意传递参数我将使用3个参数:

        public function __call($name,$arguments)
        {
           $this->repository->$name($argument[0],$argument[1],$argument[2]);
        }

但这对我来说似乎不切实际,也不是一个具体的解决方案,因为一种方法可以具有多个参数。那么,您可以帮我解决以下问题吗?

  1. 我将如何找出一个方法有多少参数
  2. 如何在迭代数组$arguments时传递参数?

1 个答案:

答案 0 :(得分:1)

从PHP 5.6开始,您拥有argument unpacking,可让您完全使用...之后进行操作,所以

$this->repository->$name($argument[0],$argument[1],$argument[2]);

成为...

$this->repository->$name(...$argument);

这将传递任何数字或参数,就像它们是单独的字段一样。