HiveBrain v1.2.0
Get Started
← Back to all entries
principlephpMinor

advantage of using __call method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
advantageusing__callmethod

Problem

I have wrote simple class that allowing database selection and inserts.Could you please tell me does this a right way to use __call method with any useful advantage of it ?

db = $connection;
    }
  public function __call($function, $args) {

          if ($function == 'getSelect') {
            $sql = $this->db->prepare($args[0]['query']);
            $sql->execute(array(
                $args[0]['parameters']
            ));
            return $sql->fetchALL(PDO::FETCH_OBJ);
          }

           if ($function == 'getInsert') {
            $sql = $this->db->prepare($args[0]['query']);
            $result = $sql->execute($args[0]['parameters']);
            return $result;
          }
  }
} 

$dbh = new PDO("mysql:host=127.0.0.1;dbname=" . DATABASE, USERNAME, PASSWORD, array(
    PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception
$dbFactory = new _getDatabase($dbh);
$select = array();
$insert = array();
$select['query'] = 'SELECT * FROM `branches` WHERE B_CODE = ?';
$select['parameters'] = 'AMB';

$insert['query'] = 'INSERT INTO `commition`(`date`, `reg`, `com`, `oper`) VALUES (?,?,?,?)';
$insert['parameters'] = array('2014-02-20','86869','DITEC','Asuntha');
var_dump($dbFactory->getSelect($select));
var_dump($dbFactory->getInsert($insert));
?>

Solution

You are using the __call for a completly wrong purpose. Instead of defining the functions/methods in the class itself, you are in fact defining them in a __call function.

Everytime you call a method on your current class the compiler does this:

doest the method exist? does the scope have privileges to call the method? -> call the method.

No method found? doest the object have a __call method? does the scope have privileges to call the method? -> call the method.

Now you are in the __call method. It now does a lot of string comparisons (could be 'optmized' using switch statements if a lot of calls are made).

Not really optimal, not to mention that the compiler and or other developers now have no clue at all or it/they are passing enough arguments to a method. hell

But, what is the point of the __call method then you may ask. Some argue this should never have been implemented in the first place, some love it. But that is a different argument.

Some neat examples:

  • http://www.garfieldtech.com/blog/magical-php-call



  • Laravel facades (click here for the code)

Context

StackExchange Code Review Q#48650, answer score: 4

Revisions (0)

No revisions yet.