Created
July 20, 2017 08:23
-
-
Save mageekguy/13dd3c1fa4fc4a760f982b04fb13f64e to your computer and use it in GitHub Desktop.
Dynamic method call using PCRE and match naming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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