In PHP that’s called lambda_style or Anonymous Function, to make the implementation easier create a Auxiliary Class (Dinamicmethod), now just have fun :) and test.
Don’t try it right in class Database, the method __call, was not designed to seek Anonymous Function within attributes and yes of class, so we made the class Dinamicmethod.
<?php
class DinamicMethod {
public function __construct() {
#leia sobre create_function http://php.net/manual/en/function.create-function.php
$this->inserir = create_function('', 'echo "Eu sou Uma funcao anonima";');
$this->deletar = create_function('', 'echo "Eu sou Uma funcao anonima e deleto";');
}
public function __call($metodo, $argumentos) {
#Checa se o objeto ou a classe tem uma propriedade
if (property_exists($this, $metodo)) {
#Verifica se o conteúdo da variável pode ser chamado como função
if (is_callable($this->$metodo)) {
#Chama uma dada função de usuário com um array de parâmetros
return call_user_func_array($this->$metodo, $argumentos);
}
}
}
}
class Database {
public $usuario;
public function __construct() {
#objeto de classe padrão php
$this->usuario = new DinamicMethod();
}
}
$db = new Database();
$db->usuario->deletar();
Vc means to dynamically create/add methods?
– rray
@rray, this very thing...
– MeuChapeu
your method returns some value? if yes, you can have it return the user object and call the Insert method.
– Brumazzi DB
The name of this is interface Fluent. But the magic __call() method is not normally used unless you want to transform a "non-fluent" class into an "Fluent structure".
– Daniel Omine
@Brumazzid.B., I was able to do it now... but it looks like $db->usuarios()->Insert(); it can be done without the () in the users() ?
– MeuChapeu
being a method I believe not, but if your "users" were a variable, it is possible.
– Brumazzi DB
@Brumazzid.B. Show.. managed using __get() instead of __call(). Thank you, your comments helped me unlock the thought.
– MeuChapeu
php is not my strong suit, but need only call.
– Brumazzi DB
usuarios->
would have to be a class variable, not betterusuarios()->
? I’ve rarely (ever) seen anyone do it$foo->x->z()
, but this is already very common:$foo->x()->z()
, Is there any need to want to do the way you wrote?– Guilherme Nascimento
@Guilhermenascimento, the Notorm uses in this style. I have no specific need, just wanted to know how it could be done.
– MeuChapeu
@Meuchapeu possible is yes, actually it is even easy, would be using
__get
and__set
, but it’s laborious and the worst that it can be "overwritten" (unless you do a validation on__set
) I will try to formulate an example. The call method will only work for functions.– Guilherme Nascimento
@Meuchapeu posted an example, I hope it helps.
– Guilherme Nascimento