184

私はPHP5を使用していますが、「メソッドチェーン」と呼ばれるオブジェクト指向アプローチの新機能について聞いたことがあります。正確には何ですか?どうすれば実装できますか?

4

10 に答える 10

359

本当に簡単です。すべてが元の(または他の)オブジェクトを返す一連のミューテイターメソッドがあります。そうすれば、返されたオブジェクトのメソッドを呼び出し続けることができます。

<?php
class fakeString
{
    private $str;
    function __construct()
    {
        $this->str = "";
    }
    
    function addA()
    {
        $this->str .= "a";
        return $this;
    }
    
    function addB()
    {
        $this->str .= "b";
        return $this;
    }
    
    function getStr()
    {
        return $this->str;
    }
}


$a = new fakeString();


echo $a->addA()->addB()->getStr();

これは「ab」を出力します

オンラインでお試しください!

于 2010-09-16T06:10:57.207 に答える
49

基本的に、あなたはオブジェクトを取ります:

$obj = new ObjectWithChainableMethods();

return $this;最後にを効果的に実行するメソッドを呼び出します。

$obj->doSomething();

同じオブジェクト、つまり同じオブジェクトへの参照を返すため、次のように、戻り値から同じクラスのメソッドを呼び出し続けることができます。

$obj->doSomething()->doSomethingElse();

本当にそれだけです。2つの重要なこと:

  1. お気づきのとおり、これはPHP5のみです。PHP 4ではオブジェクトを値で返すため、正しく機能しません。つまり、オブジェクトのさまざまなコピーでメソッドを呼び出しているため、コードが破損する可能性があります。

  2. 繰り返しますが、チェーン可能なメソッドでオブジェクトを返す必要があります。

    public function doSomething() {
        // Do stuff
        return $this;
    }
    
    public function doSomethingElse() {
        // Do more stuff
        return $this;
    }
    
于 2010-09-16T06:12:53.207 に答える
32

このコードを試してください:

<?php
class DBManager
{
    private $selectables = array();
    private $table;
    private $whereClause;
    private $limit;

    public function select() {
        $this->selectables = func_get_args();
        return $this;
    }

    public function from($table) {
        $this->table = $table;
        return $this;
    }

    public function where($where) {
        $this->whereClause = $where;
        return $this;
    }

    public function limit($limit) {
        $this->limit = $limit;
        return $this;
    }

    public function result() {
        $query[] = "SELECT";
        // if the selectables array is empty, select all
        if (empty($this->selectables)) {
            $query[] = "*";  
        }
        // else select according to selectables
        else {
            $query[] = join(', ', $this->selectables);
        }

        $query[] = "FROM";
        $query[] = $this->table;

        if (!empty($this->whereClause)) {
            $query[] = "WHERE";
            $query[] = $this->whereClause;
        }

        if (!empty($this->limit)) {
            $query[] = "LIMIT";
            $query[] = $this->limit;
        }

        return join(' ', $query);
    }
}

// Now to use the class and see how METHOD CHAINING works
// let us instantiate the class DBManager
$testOne = new DBManager();
$testOne->select()->from('users');
echo $testOne->result();
// OR
echo $testOne->select()->from('users')->result();
// both displays: 'SELECT * FROM users'

$testTwo = new DBManager();
$testTwo->select()->from('posts')->where('id > 200')->limit(10);
echo $testTwo->result();
// this displays: 'SELECT * FROM posts WHERE id > 200 LIMIT 10'

$testThree = new DBManager();
$testThree->select(
    'firstname',
    'email',
    'country',
    'city'
)->from('users')->where('id = 2399');
echo $testThree->result();
// this will display:
// 'SELECT firstname, email, country, city FROM users WHERE id = 2399'

?>
于 2015-09-27T03:52:51.060 に答える
14

静的メソッドチェーンの別の方法:

class Maker 
{
    private static $result      = null;
    private static $delimiter   = '.';
    private static $data        = [];

    public static function words($words)
    {
        if( !empty($words) && count($words) )
        {
            foreach ($words as $w)
            {
                self::$data[] = $w;
            }
        }        
        return new static;
    }

    public static function concate($delimiter)
    {
        self::$delimiter = $delimiter;
        foreach (self::$data as $d)
        {
            self::$result .= $d.$delimiter;
        }
        return new static;
    }

    public static function get()
    {
        return rtrim(self::$result, self::$delimiter);
    }    
}

呼び出し

echo Maker::words(['foo', 'bob', 'bar'])->concate('-')->get();

echo "<br />";

echo Maker::words(['foo', 'bob', 'bar'])->concate('>')->get();
于 2017-04-04T09:57:06.387 に答える
13

メソッドチェーンとは、メソッド呼び出しをチェーンできることを意味します。

$object->method1()->method2()->method3()

これは、method1()がオブジェクトを返す必要があり、method2()にmethod1()の結果が与えられることを意味します。次に、Method2()は戻り値をmethod3()に渡します。

良い記事:http ://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html

于 2010-09-16T06:11:51.953 に答える
5

49行のコードがあり、次のように配列上でメソッドをチェーンできます。

$fruits = new Arr(array("lemon", "orange", "banana", "apple"));
$fruits->change_key_case(CASE_UPPER)->filter()->walk(function($value,$key) {
     echo $key.': '.$value."\r\n";
});

PHPの70個のarray_関数をすべてチェーンする方法を示すこの記事を参照してください。

http://domexception.blogspot.fi/2013/08/php-magic-methods-and-arrayobject.html

于 2013-08-06T08:45:20.010 に答える
2

流暢なインターフェースを使用すると、メソッド呼び出しを連鎖させることができます。これにより、同じオブジェクトに複数の操作を適用するときに、型指定された文字が少なくなります。

class Bill { 

    public $dinner    = 20;

    public $desserts  = 5;

    public $bill;

    public function dinner( $person ) {
        $this->bill += $this->dinner * $person;
        return $this;
    }
    public function dessert( $person ) {
        $this->bill += $this->desserts * $person;
        return $this;
    }
}

$bill = new Bill();

echo $bill->dinner( 2 )->dessert( 3 )->bill;
于 2020-09-18T05:11:38.417 に答える
0

これが最も適切な答えだと思います。

<?php

class Calculator
{
  protected $result = 0;

  public function sum($num)
  {
    $this->result += $num;
    return $this;
  }

  public function sub($num)
  {
    $this->result -= $num;
    return $this;
  }

  public function result()
  {
    return $this->result;
  }
}

$calculator = new Calculator;
echo $calculator->sum(10)->sub(5)->sum(3)->result(); // 8
于 2020-08-12T08:08:32.860 に答える
-1

以下は、データベース内のIDで検索できる私のモデルです。with($ data)メソッドは関係の追加パラメーターなので、オブジェクト自体である$thisを返します。私のコントローラーでは、それをチェーンすることができます。

class JobModel implements JobInterface{

        protected $job;

        public function __construct(Model $job){
            $this->job = $job;
        }

        public function find($id){
            return $this->job->find($id);
        }

        public function with($data=[]){
            $this->job = $this->job->with($params);
            return $this;
        }
}

class JobController{
    protected $job;

    public function __construct(JobModel $job){
        $this->job = $job;
    }

    public function index(){
        // chaining must be in order
        $this->job->with(['data'])->find(1);
    }
}
于 2017-02-02T06:02:11.097 に答える
-1

JavaScriptのようにメソッドチェーンを意味する場合(またはjQueryを念頭に置いている人もいます)、その開発者をもたらすライブラリを利用してみませんか。PHPの経験はありますか?たとえば、Extras- https://dsheiko.github.io/extras/これは、JavaScriptとUnderscoreメソッドを使用してPHPタイプを拡張し、チェーンを提供します。

特定のタイプをチェーンできます。

<?php
use \Dsheiko\Extras\Arrays;
// Chain of calls
$res = Arrays::chain([1, 2, 3])
    ->map(function($num){ return $num + 1; })
    ->filter(function($num){ return $num > 1; })
    ->reduce(function($carry, $num){ return $carry + $num; }, 0)
    ->value();

また

<?php
use \Dsheiko\Extras\Strings;
$res = Strings::from( " 12345 " )
            ->replace("/1/", "5")
            ->replace("/2/", "5")
            ->trim()
            ->substr(1, 3)
            ->get();
echo $res; // "534"

または、ポリモーフィックにすることもできます。

<?php
use \Dsheiko\Extras\Any;

$res = Any::chain(new \ArrayObject([1,2,3]))
    ->toArray() // value is [1,2,3]
    ->map(function($num){ return [ "num" => $num ]; })
    // value is [[ "num" => 1, ..]]
    ->reduce(function($carry, $arr){
        $carry .= $arr["num"];
        return $carry;

    }, "") // value is "123"
    ->replace("/2/", "") // value is "13"
    ->then(function($value){
      if (empty($value)) {
        throw new \Exception("Empty value");
      }
      return $value;
    })
    ->value();
echo $res; // "13"
于 2018-04-12T09:13:08.240 に答える