$i->php();

Hãy tiết kiệm điện và sử dụng opensource để bảo vệ môi trường

method chaining php

Trong một số thư viện của PHP người ta thường dùng method chaining để viết code ngắn gọn và đẹp hơn .

Doctrine là một ORM framework tận dụng triệt để cách viết này , một số khác có thể thấy trong các thư viện của Zend Framework .

Doctrine :


from('User u')
          ->leftJoin('u.Phonenumber p')
          ->execute();
?>

Zend Framework :


$mail = new Zend_Mail();
$mail->setBodyText('This is the text of the mail.')
  ->setFrom('somebody@example.com', 'Some Sender')
  ->addTo('somebody_else@example.com', 'Some Recipient')
  ->setSubject('TestSubject')
  ->send();

Trong khi cách viết thông thường là :


$mail = new Zend_Mail();
$mail->setBodyText('This is the text of the mail.');
$mail->setFrom('somebody@example.com', 'Some Sender');
$mail->addTo('somebody_else@example.com', 'Some Recipient');
$mail->setSubject('TestSubject');
$mail->send();

Rõ ràng sử dụng method chaining đẹp và ngắn gọn hơn nhiều .

để làm được điều này , rất đơn giản . Ở các phương thức cho phép tiếp tục gọi tiếp sẽ return về đối tượng $this .


public function foo() {
  ... do something ...
  return $this;
}

lúc này có thể gọi như sau $myobject->foo()->bar()->baz()->bat();


About The Author

habogay

Comments

Leave a Reply