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 :
$users = Doctrine_Query::create()
->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();
Cam on thong tin tuyet voi
Trả lờiXóa