B
B
boss-feeeddd2015-11-21 15:16:28
Yii
boss-feeeddd, 2015-11-21 15:16:28

How to generate Yii2 createUrl address?

Hello. The crux of the matter is as follows. I have a table: content with fields id, name, slug. In the table I am going to store dynamically created pages. In the slug field, I store the URL of the page.
Installed pure Yii2. In config/web.php specified:

'urlManager' => [
      'enablePrettyUrl' => true,
      'showScriptName' => false,
      'rules' => [

               '/' => 'page/index',
              ['class' => 'app\components\CarUrlRule', 'connectionID' => 'db'],

            ],
    ]

In the PageController:
namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\Url;



class ModuleController extends Controller
{


    public function actionIndex()
    {
    
        return $this->render('index');
    }

}

Made a file app/components/CarUrlRule.php
namespace app\components;

use yii\web\UrlRule;

class CarUrlRule extends UrlRule
{
   
   
    public $connectionID = 'db';

    public function init()
    {
        if ($this->name === null) {
            $this->name = __CLASS__;
        }
    }

    public function createUrl($manager, $route, $params)
    {
        if ($route === 'page/index') {
            if (isset($params['manufacturer'], $params['model'])) {
                return $params['manufacturer'] . '/' . $params['model'];
            } elseif (isset($params['manufacturer'])) {
                return $params['manufacturer'];
            }
        }
        return false;  // это правило не подходит
    }

    public function parseRequest($manager, $request)
    {
        $pathInfo = $request->getPathInfo();
        if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) {
            // check $matches[1] and $matches[3] to see
            // if they match a manufacturer and a model in the database
            // If so, set $params['manufacturer'] and/or $params['model']
            // and return ['car/index', $params]
        }
        return false;  // это правило не подходит
    }

How to make it so that when opening the site-address.ru/page name, the page address from the slug is taken from the database and opened? For example ,
site-address.ru/about
site-address.ru/contact
site-address.ru/qwerty
_ didn't really understand. Googled a lot, but the examples are the same. Question: 1) How to make a page open from the database? 2) What should be written in the controller? 3) What else needs to be written in the CarUrlRule.php file?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
matperez, 2015-11-21
@boss-feeeddd

In principle, you only need one rule in the config:

[
    '<slug:[\w\/-]+>' => '/page/view',
]

In the PageController::viewAction() action, get the slug parameter, use it to get the page from the database and show it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question