使用 php 的 __call 方法调整 class:传递参数
Adapting a class Using php's __call method: Passing the parameters
基于 answer 在我的 Symfony 3.4 项目上,我想到了使用神奇的 __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]);
}
但这似乎不切实际,对我来说不是具体的解决方案,因为一个方法可以有多个参数。我觉得我需要解决以下问题:
- 我如何知道一个方法有多少个参数?
- 如何在迭代数组时传递参数
$arguments
?
从 PHP 5.6 开始,您拥有 argument unpacking,它允许您在使用 ...
后完全按照自己的意愿行事,因此
$this->repository->$name($argument[0],$argument[1],$argument[2]);
变成...
$this->repository->$name(...$argument);
这将传递任何数字或参数,就像它们是单独的字段一样。
基于 answer 在我的 Symfony 3.4 项目上,我想到了使用神奇的 __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]);
}
但这似乎不切实际,对我来说不是具体的解决方案,因为一个方法可以有多个参数。我觉得我需要解决以下问题:
- 我如何知道一个方法有多少个参数?
- 如何在迭代数组时传递参数
$arguments
?
从 PHP 5.6 开始,您拥有 argument unpacking,它允许您在使用 ...
后完全按照自己的意愿行事,因此
$this->repository->$name($argument[0],$argument[1],$argument[2]);
变成...
$this->repository->$name(...$argument);
这将传递任何数字或参数,就像它们是单独的字段一样。