Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamic method call using PCRE and match naming
<?php
class foo
{
function findAllAgentsBy()
{
var_dump(__METHOD__, func_get_args());
}
function findOneAgentBy()
{
var_dump(__METHOD__, func_get_args());
}
function findAllOrganismesBy()
{
var_dump(__METHOD__, func_get_args());
}
function findOneOrganismeBy()
{
var_dump(__METHOD__, func_get_args());
}
function findAllSitesBy()
{
var_dump(__METHOD__, func_get_args());
}
function findOneSiteBy()
{
var_dump(__METHOD__, func_get_args());
}
function findAllEntitesBy()
{
var_dump(__METHOD__, func_get_args());
}
function findOneEntiteBy()
{
var_dump(__METHOD__, func_get_args());
}
function findAllPhotosBy()
{
var_dump(__METHOD__, func_get_args());
}
function findOnePhotoBy()
{
var_dump(__METHOD__, func_get_args());
}
function __call($method, $arguments)
{
if (! sizeof($arguments)) {
throw new \Exception('Cette méthode requiert des arguments');
}
if (! preg_match('/^(?P<method>find(?:One|All).*By)(?P<fieldName>.+)$/', $method, $matches) || ! method_exists($this, $matches['method'])) {
throw new \Exception("Cette méthode n'existe pas");
}
$arguments[0] = array($matches['fieldName'] => $arguments[0]);
return call_user_func_array(array($this, $matches['method']), $arguments);
}
}
(new foo)->findOneSiteByFoo(range(0, 5));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment