How to make a dynamic method?

Asked

Viewed 30 times

0

I have two methods a loadById and loadByCpf, I would like to create a single method, ex: loadClient, as I do?

public function loadByCpf($cpfcust)
        {
            $sql = new Sql();
            $results = $sql->select("SELECT * FROM tb_custumer WHERE cpfcust = :cpfcust", array(
                ":cpfcust"=>$cpfcust
            ));
}

public function loadById($idcust)
        {
            $sql = new Sql();
            $results = $sql->select("SELECT * FROM tb_custumer WHERE idcust = :idcust", array(
                ":idcust"=>$idcust
            ));
}
  • 1

    What have you tried? What problem have you had?

1 answer

1


You can create only one method that uses interpolation. Follow the example:

    public function loadBy($key, $withValue)
    {

        $bind = ":{$key}";

        $sql = new Sql();
        $results = $sql->select("SELECT * FROM tb_custumer WHERE {$key} = {$bind}", array(
            $bind => $withValue
        ));

    }

And just call the method in your class:

$this->loadBy('idcust', 10);

Or you can create a more efficient method using the honeybee method_ _

public function __call__($name, $arguments)
{

    if(strpos($name, 'loadBy') !== FALSE){
        $key = strtolower(str_replace('loadBy', '', $name));
        $this->loadBy($key, $arguments);
    }

}

And in your function to call

$this->loadByCpf(10);
$this->loadByName('John Doe');
$this->loaderEmail('[email protected]');

But you always need to be careful and pay attention if you are passing the correct parameters according to the name of the fields in your table.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.