デコレータパターンが必要なコードを作成しているので、__callの魔法の方法を使用して使用することを本当に簡単にしたいと考えていました。__callを使用しているときに参照で引数を渡すには
デコレータパターン(ここでは、シングルトンを追加するにはいくつかのメソッドを追加し、いくつかは禁止する)を使用すると、メソッドの一部をオーバーライドする必要はありません。したがって、__callを使用すると、コードを簡素化することができます。
私の状況は、いくつかのメソッドが参照渡しの引数を必要とするときに発生します。
たとえば、PDOをデコレートするXPDOクラスを作成しました。私の前者ではありませんが、私はそれを示すことはできません。
<?php
class XPDO{
private static $dbInstance=null;
private $pdoConnexion;
static function getInstance(){
if(self::$dbInstance ==null){
self::$dbInstance = new XPDO(/*tes params*/);
}
return self::$dbInstance;
}
private function __clone(){
}
private function __construct(){
$this->pdoConnexion = new PDO('mysql:localhost;dbname=blog','root','');
}
/**
*on possède toutes les méthodes de PDO mais en plus certaines qui nous sont propres ou qui
*surchargent/limitent celles de PDO si telles qu'elles sont implémentées dans PDO, on ne les aime pas.
*/
public function __call($method, $args){
if(is_callable(array($this,$method))){
return call_user_func_array(array($this,$method),$args);
}else if(is_callable(array($this->pdoConnexion,$method))){
return call_user_func_array(array($this->pdoConnexion,$method),$args);
}
}
/**
*
*@param string $query the query we want to add the where
*@param string $param name of the column
*@return string the identifier that we would use to bind a value
*/
private function addAndWhere(&$query,$param){
$uid = rand(1,100000);
if(strpos($query,'WHERE')){
$query.= ' AND '.$param.'=:'.$param.$uid;
}else{
$query.= ' WHERE '.$param.'=:'.$param.$uid;
}
return $param.$uid;
}
}
$pdo = XPDO::getInstance();
$query = 'SELECT * FROM sometable';
var_dump($pdo->addAndWhere($query,'smth'));
var_dump($query);
これは、addAndWhereが参照とコピーを期待するため、これは失敗します。 このコードは、addAndWhereをpublicに渡すことで簡単に修正でき、センスがあります。ここは単なる例です。今、参照を必要とするのはPDOであり、あなたは私の意見を持っていると想像してください。
ご協力ありがとうございます。私は今何をしなければならないかを知っています。 – artragis