복붙노트

PHP는 방법 체인?

PHP

PHP는 방법 체인?

저는 PHP 5를 사용하고 있으며 객체 지향 접근 방식 인 '메소드 체인 (method chaining)'이라는 새로운 기능에 대해 들어 봤습니다. 정확히 무엇입니까? 어떻게 구현합니까?

해결법

  1. ==============================

    1.그것의 오히려 간단하게, 당신은 일련의 뮤 테이터 (mutator) 메소드를 가지고 있습니다. 모든 메소드는 원래의 (또는 다른) 객체를 리턴합니다. 그렇게하면 리턴 된 객체에서 메소드를 계속 호출 할 수 있습니다.

    그것의 오히려 간단하게, 당신은 일련의 뮤 테이터 (mutator) 메소드를 가지고 있습니다. 모든 메소드는 원래의 (또는 다른) 객체를 리턴합니다. 그렇게하면 리턴 된 객체에서 메소드를 계속 호출 할 수 있습니다.

    <?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"

    온라인으로 사용해보십시오!

  2. ==============================

    2.기본적으로 객체를 사용합니다.

    기본적으로 객체를 사용합니다.

    $obj = new ObjectWithChainableMethods();
    

    효과적으로 $ this를 리턴하는 메소드를 호출하십시오. 결국 :

    $obj->doSomething();
    

    동일한 객체 또는 오히려 동일한 객체에 대한 참조를 반환하기 때문에 다음과 같이 동일한 클래스의 메서드를 반환 값에서 계속 호출 할 수 있습니다.

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

    그게 사실입니다. 두 가지 중요한 사항 :

  3. ==============================

    3.이 코드를보십시오 :

    이 코드를보십시오 :

    <?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'
    
    ?>
    
  4. ==============================

    4.메서드 연쇄는 메서드 호출을 연결할 수 있음을 의미합니다.

    메서드 연쇄는 메서드 호출을 연결할 수 있음을 의미합니다.

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

    즉, method1 ()은 객체를 반환해야하고 method2 ()는 method1 ()의 결과가 반환됩니다. 그런 다음 Method2 ()는 return 값을 method3 ()에 전달합니다.

    좋은 문서 : http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html

  5. ==============================

    5.다음과 같이 배열에 메소드를 연결할 수있는 49 행의 코드가 있습니다.

    다음과 같이 배열에 메소드를 연결할 수있는 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

  6. ==============================

    6.

    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();
    
  7. ==============================

    7.

    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);
        }
    }
    
  8. ==============================

    8.JavaScript (또는 일부 사람들은 jQuery를 염두에 두어야 함)와 같은 메소드 체인을 의미하는 경우 해당 개발자를 데려 오는 라이브러리를 가져 가지 마십시오. PHP에서의 경험? 예를 들어 Extras - https://dsheiko.github.io/extras/ JavaScript 및 Underscore 메서드를 사용하여 PHP 유형을 확장하고 체인을 제공합니다.

    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"
    
  9. from https://stackoverflow.com/questions/3724112/php-method-chaining by cc-by-sa and MIT license