Quantcast
Channel: Live News for Yii Framework
Viewing all articles
Browse latest Browse all 3375

[Wiki] How to get SEO friendly URL using Model and new getUrl() function

$
0
0

We all need SEO friendly URLs for our projects. its not always good to call route with params so we can generalise it for all models using a common function.

Following the general convention of model and control sharing common name, we can use this code to get seo friendly URL.

public function getControllerID() {
        $modelClass = get_class ( $this );
        $pos = strrpos ( $modelClass, '\\' );
        $class = substr ( $modelClass, $pos + 1 );
        return Inflector::camel2id ( $class );
    }
    public function getUrl($action = 'view', $id = null) {
        $params = [ 
                $this->getControllerID () . '/' . $action 
        ];
        if ($id != null)
            $params ['id'] = $id;
        else
            $params ['id'] = $this->id;
        // add the title parameter to the URL
        $params ['title'] = ( string ) $this;
        // absolute url
        return Yii::$app->getUrlManager ()->createAbsoluteUrl ( $params, true );
    }

In code code where ever you need to url to a model , you just call $model->url or $model->getUrl('view').

You may have to additionally update urlManager in config with rules for pretty url.

'<controller:[A-Za-z-]+>/<id:\d+>/<title>' => '<controller>/view',
                                '<controller:[A-Za-z-]+>/<id:\d+>' => '<controller>/view',
                                '<controller:post>/<id:\d+>/<title>' => 'blog/view',
                                '<controller:[A-Za-z-]+>/<action:[A-Za-z-]+>/<id:\d+>/<title>' => '<controller>/<action>',
                                '<controller:[A-Za-z-]+>/<action:[A-Za-z-]+>/<id:\d+>' => '<controller>/<action>',

you will get url like this.

http://localhost/link/650/need-a-professional-developer


Viewing all articles
Browse latest Browse all 3375

Trending Articles