很多php開發(fā)朋友都沒有弄清楚Trait(性狀)。這是PHP5.4.0引入的新概念,既像類又像接口。性狀是類的補(bǔ)分實(shí)現(xiàn)(即常量、屬性、方法),可以混入一個(gè)或者多個(gè)現(xiàn)有的PHP類中。 性狀有兩個(gè)作用:表明類可以做什么(像是接口);提供模塊化實(shí)現(xiàn)(像是類)。 PHP使用一種典型的繼承模型,在這種模型中,我們先編寫一個(gè)通用的根類,實(shí)現(xiàn)基本功能,然后擴(kuò)展這個(gè)根類,創(chuàng)建更具體的類,從直接父類繼承實(shí)現(xiàn)。這叫繼承層次結(jié)構(gòu),很多編程語言都使用了這個(gè)模式 大多時(shí)候,這種典型的繼承模型能良好的運(yùn)行,可是,如果想讓兩個(gè)無關(guān)的PHP類具有類似的行為,應(yīng)該怎么做呢?
假如Shop和Car兩個(gè)PHP類的作用十分不同,而且在繼承層次結(jié)構(gòu)中沒有共同的父類。 那么這兩個(gè)類都應(yīng)該能使用地理編碼技術(shù)轉(zhuǎn)化成經(jīng)緯度,然后在地圖上顯示。要怎么解決這個(gè)問題呢?
創(chuàng)建一個(gè)父類讓Shop和Car都繼承它 創(chuàng)建一個(gè)接口,定義實(shí)現(xiàn)地理編碼功能需要哪些方法,然后讓Shop和Car兩個(gè)類都實(shí)現(xiàn)這個(gè)接口 創(chuàng)建一個(gè)性狀,定義并實(shí)現(xiàn)地理編碼相關(guān)的方法,然后把在Shop和Car兩個(gè)類中混入這個(gè)性狀 第一種解決方法不好,因?yàn)槲覀儚?qiáng)制讓兩個(gè)無關(guān)的類繼承同一個(gè)祖先,而很明顯,這個(gè)祖先不屬于各自的繼承層次結(jié)構(gòu)。
第二種解決方法好,因?yàn)槊總€(gè)類都能保有自然的繼承層次結(jié)構(gòu)。但是,我們要在兩個(gè)類中重復(fù)實(shí)現(xiàn)的地理編碼功能,這不符合DRY原則。 注:DRY是 Don’t Repeat Yourself(不要自我重復(fù))的簡(jiǎn)稱,表示不要在多個(gè)地方重復(fù)編寫相同的代碼,如果需要修改遵守這個(gè)原則編寫的代碼,只需要在一出修改,改動(dòng)就能體現(xiàn)到其他地方。
第三種解決方法最好,這么做不會(huì)攪亂這兩個(gè)類原本自然的繼承層次結(jié)構(gòu)。
如何創(chuàng)建性狀?
trait Geocodable { // 這里是性狀的實(shí)現(xiàn)}如何使用性狀?
class Shop{ use Geocodable; // 這里是類的實(shí)現(xiàn)}例子 創(chuàng)建一個(gè)Geocodable 性狀
trait Geocodable { /** * 地址 * @var string */ PRotected $address; /** * 編碼器對(duì)象 * @var /Geocoder/Geocoder */ protected $geocoder; /** * 處理后結(jié)果對(duì)象 * @var /Geocoder/Result/Geocoded */ protected $geocoderResult; //注入Geocoder對(duì)象 public function setGeocoder(/Geocoder/GeocoderInterface $geocoder) { $this->geocoder = $geocoder; } //設(shè)定地址 public function setAddress($address) { $this->address = $address; } //返回緯度 public function getLatitude() { if (isset($this->geocoderResult) === false) { $this->geocodeAddress(); } return $this->geocoderResult->getLatitude(); } //返回經(jīng)度 public function getLongitude() { if (isset($this->geocoderResult) === false) { $this->geocodeAddress(); } return $this->geocoderResult->getLongitude(); } //把地址字符串傳給Geocoder實(shí)例,獲取經(jīng)地理編碼器處理得到的結(jié)果 protected function geocodeAddress() { $this->geocoderResult = $this->geocoder->geocode($this->address); return true; }}使用性狀
$geocoderAdapter = new /Geocoder/HttpAdapter/CurlHttpAdapter();$geocoderAdapter = new /Geocoder/Provider/GoogleMapsProvider($geocoderAdapter);$geocoder = new /Geocoder/Geocoder($geocoderProvider);$store = new Shop();$store->setAddress('420 9th Avenue, New York, NY 10001 USA');$store->setGeocoder($geocoder);$latiude = $store->getLatitude();$longitude = $store->getLongitude();echo $latitude, ':', $longitude;新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注