Facebook'taki PHP grubunda birisi boyle bir istekde bulunmus. Siniftan sadece tek bir "instance" uretmek, daha sonra istenildiginde ise bir Exception vermesi isteniyordu.
PHP5.4'un nimaetlerinden traitler yardimiyla bunu hazirladim. Guzel bir ornek olacagini dusunuyorum.
Trait kullanilarak hazirlanan sinif ilk getInstance() metodu kullanildiginda sinifin bir ornegini gonderecek, bir dahaki cagirildiginda ise DisposableClassException gonderecektir. Bunu yakalamak da size kalmis. :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DisposableClassException extends \Exception | |
{} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait DisposableClassTrait | |
{ | |
protected static $used = false; | |
final public static function getInstance() | |
{ | |
if (static::$used) { | |
throw new DisposableClassException('This class is disposable!'); | |
} | |
static::$used = true; | |
return new static; | |
} | |
final private function __construct() { | |
$this->init(); | |
} | |
protected function init() { | |
echo 'Hey guys! Im from ' . __CLASS__ . '! :)'; | |
} | |
final private function __wakeup() {} | |
final private function __clone() {} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class OneTimeLifeExample | |
{ | |
use DisposableClassTrait; | |
} | |
// Class initialized! | |
OneTimeLifeExample::getInstance(); | |
// Exception! | |
OneTimeLifeExample::getInstance(); |
No comments:
Post a Comment