改编类使用php的__call方法:传递参数 [英] Adapting a class Using php's __call method: Passing the parameters
问题描述
基于我的Symfony 3.4项目中的 answer ,我想到了使用魔术 __ call
方法,以便有一种通用的方式来调用存储库即服务:
Based upon answer on my Symfony 3.4 project I thought of using the magic __call
method in order to have a common way to invoke repositories as a service:
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();
}
}
}
问题:
存储库方法将具有以下形式:
A repository method will have this form:
public function aMethod($param1,$param2)
{
//Some magic is done here
}
因此,如果我确切知道哪种方法,我将需要某种方式迭代数组 $ arguments
以便将参数传递给函数调用我会任意传递参数,例如,如果我知道一个方法有3个参数,我将使用该参数:
So I will need somehow to iterate the array $arguments
in order to pass the parameters to the function if I knew exactly what method would be called I would arbitatily pass the parameters, for example if I knew that a method had 3 parameters I would use:
public function __call($name,$arguments)
{
$this->repository->$name($argument[0],$argument[1],$argument[2]);
}
但这对我来说似乎不切实际,也不是一个具体的解决方案,因为方法可以超过1个参数。我想我需要解决以下问题:
But that seems impractical and not a concrete solution for me because a method can have more than 1 parameters. I think I need to solve the following problems:
- 我将如何找出一个方法有多少个参数?
- 如何在迭代数组
$ arguments
时传递参数?
- How I will find out how many parameters a method has?
- How to pass the arguments while iterating the array
$arguments
?
推荐答案
从PHP 5.6开始,您具有参数解压缩,它使您可以完全使用 ...
之后执行操作,因此
As of PHP 5.6 you have argument unpacking which allows you to do exactly what your after using ...
, so
$this->repository->$name($argument[0],$argument[1],$argument[2]);
成为...
$this->repository->$name(...$argument);
这将传递任何数字或参数,就像它们是单个字段一样。
This will pass any number or arguments as though they are individual fields.
这篇关于改编类使用php的__call方法:传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!