PHP code example of petrgrishin / yii-url-builder

1. Go to this page and download the library: Download petrgrishin/yii-url-builder library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

petrgrishin / yii-url-builder example snippets


class BaseController extends \CController {

    public function createUrlBuilder($route, $params = array()) {
        $urlBuilder = new UrlBuilder($this->getUrlManager());
        $urlBuilder
            ->setRoute($route)
            ->setParams($params);
        return $urlBuilder;
    }

    public function getUrlManager() {
        $urlManager = $this->getApp()->getUrlManager();
        return $urlManager;
    }

    public function getApp() {
        return \Yii::app();
    }
}

class SiteController extends BaseController {

    public function actionIndex() {
        return $this->render('index', array(
            'urls' => array(
                'catalog' => $this->createUrlBuilder('site/catalog')
                    ->getUrl(),
                // передана готовая строка адреса ?r=site/catalog
            ),
        ));
    }
    
    public function actionCatalog() {
        return $this->render('about', array(
            'products' => Product::model()->findAll(),
            'urls' => array(
                'product' => $this->createUrlBuilder('site/product')
                    ->setRequired(array('id')),
                // передан объект построителя с необходимыми знаниями,
                // требуемые параметры заполняются в представлении
            ),
        ));
    }
    
    public function actionProduct($id) {
        return $this->render('product');
    }
}

/** @var UrlBuilder $productUrlBuilder */
$productUrlBuilder = $this->getParam('urls.product');

foreach ($this->getParam('products') as $product) {
    $productUrl = $productUrlBuilder
        ->copy()
        ->setParam('id', $product->id)
        ->getUrl();
        
    print($productUrl);
    // строка адреса ?r=site/product&id=1
}

// или передать параметры построителя адреса в клиентский скрипт
$this->setJsParams(array(
    'urls' => array(
        'product' => $productUrlBuilder->toArray(),
    ),
));