K
K
Konstantin Andreevich2015-01-26 16:24:57
Yii
Konstantin Andreevich, 2015-01-26 16:24:57

How to implement such a fluent interface in php?

I really liked the idea of ​​a fluid interface that is used in Laravel 4 and Yii2. But, unfortunately, I cannot fully understand how such things are implemented.
Here is an example:

Route::get('/page/{id}', '[email protected]')->where(['id' => $id]);

How to implement something like this? Most importantly:
- how to implement with a static method(Route::get)?
- how to make it so that despite the fact that the parameter is passed last (where), it is available for the get method?
- and finally, how in such an example to make sure that all the necessary actions take place in the get method, and it is not just a method that returns some class.
---
UPD: look at what I have a big plug:
Route::set('11', '22')->where('33');

class Route 
{
    public static function set($uri, $action)
    {
        return new Router($uri, $action);
    }
}

class Router
{
    private $params;
    private $uri;
    private $action;

    public function __construct($uri, $action)
    {
        $this->uri    = $uri;
        $this->action = $action;

        $this->master();
    }

    public function where($params)
    {
        $this->params = $params;
    }

    public function master()
    {
        echo $this->uri . ' | ' . $this->action . ' | ' . $this->params;
    }

    // ... ниже геттеры-сеттеры

Well, it gives me only such a line "11 | 22 |". I realize that I'm calling $this-master() from the constructor when the where method hasn't fired yet. But how else? What am I missing?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
keltanas, 2015-01-26
@keltanas

Как реализовать подобное?

Да как любой текучий интерфейс.
- php.net/manual/en/function.forward-static-call.php подойдет?
- для метода get(), или чтобы интерфейс объекта, который возвращает get() имел метод where()?
- метод не может возвращать класс ни при каких обстоятельствах. А какие еще действия должны происходить в методе get() кроме return new Controller() и зачем?

T
tuxx, 2015-01-26
@tuxx

habrahabr.ru/post/170019

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question