PHP DSL Elements: Making Library APIs Easier to Use
When developing our internal framework (unfortunately, PHP generally contributes to the constant reinvention of the bicycle), we tried to design library module interfaces in such a way that the client code using these interfaces would be simple, concise and readable.
Ideally, a specialized module designed to solve a particular problem should form a simplified language that allows the developer to describe the solution or result of solving the problem as close as possible to the terms of the subject area. If at the same time we do not go beyond the framework of the programming language used, we are talking about implementing the so-called internal DSL .
A lot has been written about the implementation of DSL in various languages, for example, is available on the Fowler websitecatalog of patterns on this topic . The features of any design pattern are largely determined by the implementation language; this is doubly true for DSL patterns. Unfortunately, the range of possibilities that PHP can provide is extremely limited. Nevertheless, using two standard templates - Method Chaining and Expression Builder , you can achieve a more convenient and readable API.
Proper naming of classes and methods is half the battle when developing a DSL-style API. It is important that the methods are named as close as possible to the subject area, and not to the software implementation. It sounds corny, but you can find a lot of examples when naming is due, for example, to the implementation of one or another classic design pattern from GoF .
The use of method chains makes the code more concise and in some cases allows achieving the effect of a specialized DSL. When developing library modules, we try to follow the rule: if the method does not return a functionally necessary result, let it return
The Builder pattern allows you to more conveniently build systems of nested objects when the parent contains links to children, those, in turn, to their children and so on. Note that in PHP it is advisable to avoid bidirectional links (the parent object refers to the child, and the child refers to the parent), since the garbage collector does not work with circular links.
To create such systems, we will create a very simple base class:
Objects of this class configure the target object, a reference to which is stored in the field
Based on this class, we write the simplest DSL to describe the configuration of the application.
Now we can create a file
You can load the configuration using the call:
Of course, the matter is not limited only to configs. For example, we describe the structure of a REST application like this:
Using fast DSL-style APIs allows you to get short and well-readable code, for example, in application controller methods:
In some relatively rare cases, you can go even further. By expanding the class a little
Of course, this approach should be used within reasonable limits, but sometimes it gives a very good result.
Ideally, a specialized module designed to solve a particular problem should form a simplified language that allows the developer to describe the solution or result of solving the problem as close as possible to the terms of the subject area. If at the same time we do not go beyond the framework of the programming language used, we are talking about implementing the so-called internal DSL .
A lot has been written about the implementation of DSL in various languages, for example, is available on the Fowler websitecatalog of patterns on this topic . The features of any design pattern are largely determined by the implementation language; this is doubly true for DSL patterns. Unfortunately, the range of possibilities that PHP can provide is extremely limited. Nevertheless, using two standard templates - Method Chaining and Expression Builder , you can achieve a more convenient and readable API.
Proper naming of classes and methods is half the battle when developing a DSL-style API. It is important that the methods are named as close as possible to the subject area, and not to the software implementation. It sounds corny, but you can find a lot of examples when naming is due, for example, to the implementation of one or another classic design pattern from GoF .
The use of method chains makes the code more concise and in some cases allows achieving the effect of a specialized DSL. When developing library modules, we try to follow the rule: if the method does not return a functionally necessary result, let it return
$this
. We also usually provide a set of methods for setting the internal properties of an object, which allows you to configure object parameters inside an expression and also makes the code more concise.The Builder pattern allows you to more conveniently build systems of nested objects when the parent contains links to children, those, in turn, to their children and so on. Note that in PHP it is advisable to avoid bidirectional links (the parent object refers to the child, and the child refers to the parent), since the garbage collector does not work with circular links.
To create such systems, we will create a very simple base class:
- class DSL_Builder {
-
- protected $parent;
- protected $object;
-
- public function __construct($parent, $object) {
- $this->parent = $parent;
- $this->object = $object;
- }
-
- public function __get($property) {
- switch ($property) {
- case 'end':
- return $this->parent ? $this->parent : $this->object;
- case 'object':
- return $this->$property;
- default:
- throw new Core_MissingPropertyException($property);
- }
- }
-
- public function __set($property, $value) { throw new Core_ReadOnlyObjectException($this); }
-
- public function __isset($property) {
- switch ($property) {
- case 'object':
- return isset($this->$property);
- default:
- return false;
- }
- }
-
- public function __unset($property) { throw new Core_ReadOnlyObjectException($this); }
-
- public function __call($method, $args) {
- method_exists($this->object, $method) ?
- call_user_func_array(array($this->object, $method), $args) :
- $this->object->$method = $args[ 0];
- return $this;
- }
- }
- ?>
Objects of this class configure the target object, a reference to which is stored in the field
$object
, delegating to it a call to methods and setting properties. Of course, the builder object can also define a set of its own methods for more complex configuration of the target object. In this case, the pseudo- end
property allows you to return to the builder of the parent object, and so on. Based on this class, we write the simplest DSL to describe the configuration of the application.
- class Config_DSL_Builder extends DSL_Builder {
-
- public function __construct(Config_DSL_Builder $parent = null, stdClass $object = null) {
- parent::__construct($parent, Core::if_null($object, new stdClass()));
- }
-
- public function load($file) {
- ob_start();
- include($file);
- ob_end_clean();
- return $this;
- }
-
- public function begin($name) {
- return new Config_DSL_Builder($this, $this->object->$name = new stdClass());
- }
-
- public function __get($property) {
- return (strpos($property, 'begin_') === 0) ?
- $this->begin(substr($property, 6)) :
- parent::__get($property);
- }
-
- public function __call($method, $args) {
- $this->object->$method = $args[ 0];
- return $this;
- }
- }
- ?>
Now we can create a file
config.php
in which to describe the configuration of our application in this form:- $this->
- begin_db->
- dsn('mysql://user:password@localhost/db')->
- end->
- begin_cache->
- dsn('dummy://')->
- default_timeout(300)->
- timeouts(array(
- 'front/index' => 300,
- 'news/most_popular' => 300,
- 'news/category' => 300))->
- end->
- begin_site->
- begin_from->
- top_limit(7)->
- end->
- begin_news->
- most_popular_limit(5)->
- end->
- end;
- ?>
You can load the configuration using the call:
- $config = Config_DSL::Builder()->load('config.php');
- ?>
Of course, the matter is not limited only to configs. For example, we describe the structure of a REST application like this:
- WS_REST_DSL::Application()->
- media_type('html', 'text/html', true)->
- media_type('rss', 'application/xhtml+xml')->
- begin_resource('gallery', 'App.Photo.Gallery', 'galleries/{id:\d+}')->
- for_format('html')->
- get_for('{page_no:\d+}', 'index')->
- post_for('vote', 'vote')->
- index()->
- end->
- end->
- begin_resource('index', 'App.Photo.Index')->
- for_format('rss')->
- get('index_rss')->
- get_for('top', 'top_rss')->
- end->
- for_format('html')->
- get_for('{page_no:\d+}', 'index')->
- index()->
- end->
- end->
-
- end;
- ?>
Using fast DSL-style APIs allows you to get short and well-readable code, for example, in application controller methods:
- public function index($page_no = 1) {
- $pager = Data_Pagination::pager($this->db->photo->galleries->count(), $page_no, self::PAGE_LIMIT);
-
- return $this->html('index')->
- with(array(
- 'top' => $this->db->photo->galleries->most_important()->select(),
- 'pager' => $pager,
- 'galleries' => $this->db->photo->galleries->
- published()->
- paginate_with($pager)->
- select()));
- }
- ?>
In some relatively rare cases, you can go even further. By expanding the class a little
DSL_Builder
, you can describe not only a static structure, but also a set of actions, that is, a certain scenario. For example, you can work with the Google AdWords API like this:- Service_Google_AdWords_DSL::Script()->
- for_campaign($campaign_id)->
- for_ad_group($group_id)->
- for_each('text', 'keyword1', 'keyword2', 'keyword3')->
- add_keyword_criteria()->
- bind('text')->
- end->
- end->
- add_ad()->
- with('headline', 'headline',
- 'displayUrl', 'www.techart.ru',
- 'destinationUrl', 'http://www.techart.ru/',
- 'description1', 'desc1',
- 'description2', 'desc2')->
- format("Ad Created")->
- end->
- end->
- end->
- for_each_campaign()->
- format("Campaign: %d, %s\n", 'campaign.id', 'campaign.name')->
- dump('campaign')->
- for_each_ad_group()->
- format("Ad group: %d, %s\n", 'ad_group.id', 'ad_group.name')->
- for_each_criteria()->
- format("Criteria: %d, %s\n", 'criteria.id', 'criteria.text')->
- end->
- end->
- end->
- end->
- run_for(Service_Google_AdWords::Client()->
- useragent('user agent')->
- email('email@domain.com'));
- ?>
Of course, this approach should be used within reasonable limits, but sometimes it gives a very good result.