REST API, URL::to() and versions

Hey guys,

I’m currently working on a REST API for our application and am running into the following issue. I’m generating links as follows:




    public function getLinks()

    {

        return [

            Link::REL_SELF => Url::to(['/v1/nodes', 'id' => $this->uid], true),

        ];

    }



As you can see I need to specify “v1” above to ensure that the link doesn’t break. But what do I do when v2 is released and this code is being executed? I would like this to upgrade automatically depending on the version that was used in the request.

What is considered good practice here. And how would I go about implementing what I want?

Thanks.

[color="#006400"]/* Moved from "General Discussions" to "REST apis" */[/color]

Firstly i think it’s a really bad idea to generate the links from the model, horrible actually, but this is what we have and we have to work with it…

Here’s how i do it:




$v = module() && preg_match('/^v(\d+)$/', module()->id) ? '/' . module()->id : '';

return [

                Link::REL_SELF => url([$v . '/whatever/view'], true),

            ];



Where module() and url() are simple functions defined as:




if (!function_exists('app')) {

    function app() {

        return \Yii::$app;

    }

}

if (!function_exists('url')) {

    function url($url = '', $scheme = false) {

        return call_user_func_array(['\yii\helpers\Url', 'to'], func_get_args());

    }

}

if (!function_exists('module')) {

    function module($name = null) {

        if ($name === null) {

            return app()->controller ? app()->controller->module : null;

        }

        return app()->getModule($name);

    }

}