Preface
A former colleague changed jobs and was asked about PHP's trait in the interview. Because no use, so did not answer well, I probably used a few times, think of the following summary to organize.
Trait
Trait are specific properties or methods that should be available in some classes (class), while other classes of the half-class should avoid using these properties and methods.
Of course, this is also related to the developer of the abstract ability of the class, some abstract ability, can reduce the use of trait but this situation should be unavoidable or trait appear meaningless.
Another situation is that when using trait, you can play a role in constraining developers and alerting developers to the need to invoke certain properties and methods of trait during development.
Colleagues put forward a good question, interface (interface) is not this role?
No hurry, let's look at an example:
For example, you want to collect all kinds of data on the website, developed Spider class . Spider has a method called request() responsible request.
<?php namespace Xwsoul\network;class spider{Public function request ($url) {//do sth.}}
But in the process of collecting data, some websites are sensitive to spiders and some are not. For sensitive Web sites, we provide a solution that uses proxies. However, the use of proxies can affect the crawl speed. This results in some of the Spider's subclasses need to use the proxy, but can not use the agent to try to use the situation.
So this time we have added a trait Proxy:
<?php namespace xwsoul\network;trait proxy{protected $isProxy = false; Public function UseProxy ($proxy) {//do STH Pro XY setups. $this->isproxy = true; return $this; The Public Function request ($url) {if (! $this->isproxy) { throw new Exception ("* * using Proxy.");}//do sth. Re Turn parent::request ($url); }}
Trait overrides the Spider's request() method, qualifying the call to throw an exception without invoking the proxy.
Back to the previous question, what is the difference between the usage and interface (interface) of trait?
The constraint of the interface is that the initial definition must be implemented, he can constrain the implementation of the method, but cannot constrain the invocation of the method, trait is a post-call, he has implemented the method, the key is that he only swapped with his own class to produce constraints (nonsense), but not to call their own classes do not have an impact ( Another nonsense), and he is reusable, and does not destroy the spider's own implementation of the increase, spider or the spider.
I think the use of trait has been very effective here.
Something
Someone might decide to implement another request like, "Proxyrequst"? What you say is good and reasonable ... But what if I used a different agent to have specifics on the request? Do you keep the if if if in the code? Why should trait give up such a refreshing solution?