且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从后端到前端Yii2高级应用程序

更新时间:2023-10-11 15:03:10

in你的前端配置将它添加到顶部以定义2个变量。

in your frontend config add this to the top to define 2 variables.

use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '/frontend/web', (new Request)->getBaseUrl());
$backEndBaseUrl = str_replace('/frontend/web', '/backend/web', (new Request)->getBaseUrl());

并将这些变量设置为组件中的baseUrl参数

And set these variables as the baseUrl parameters in the components

'components' => [
    'urlManager' => [
        'class' => 'yii\web\urlManager',
        'enablePrettyUrl' => false,
        'showScriptName' => false,
        //'baseUrl' => '/frontend/web',
        'baseUrl'=> $baseUrl,
    ],
    'urlManagerBackEnd' => [
        'class' => 'yii\web\urlManager',
        'enablePrettyUrl' => false,
        'showScriptName' => false,
        //'baseUrl' => '/backend/web',
        'baseUrl' => $backEndBaseUrl,
    ],

然后你可以拥有从前端到后端的链接例如

then you can have links from the frontend to the backend by e.g.

$backendUrl= Yii::$app->urlManagerBackEnd->createUrl('//');
echo yii\helpers\Html::a('link to backend', $backendUrl);

从后端到前端的相同内容将其添加到后端配置中:

to have the same from the backend to the frontend add this to the backend config:

use \yii\web\Request;
$baseUrl = str_replace('/backend/web', '/backend/web', (new Request)->getBaseUrl());
$frontEndBaseUrl = str_replace('/backend/web', '/frontend/web', (new Request)->getBaseUrl());

以及组件中:

'urlManager' => [
        'class' => 'yii\web\urlManager',
        'enablePrettyUrl' => false,
        'showScriptName' => false,
        'baseUrl'=> $baseUrl,
    ],
    'urlManagerFrontEnd' => [
        'class' => 'yii\web\urlManager',
        'enablePrettyUrl' => false,
        'showScriptName' => false,
        //'baseUrl' => '/backend/web',
        'baseUrl' => $frontEndBaseUrl,
    ],

并创建链接使用:

$frontendUrl= Yii::$app->urlManagerFrontEnd->createUrl('//');
echo yii\helpers\Html::a('link to frontend', $frontendUrl);

忘了你当然也可以链接到特定页面,例如从后端到前端网站/关于:

forgot you can of course also link to specific pages e.g. from backend to frontend site/about:

$frontendUrl= Yii::$app->urlManagerFrontEnd->createUrl('/site/about');
echo yii\helpers\Html::a('link to frontend site about', $frontendUrl);

BTW。如果你已经删除某些htaccess的/ web行为,你也应该在变量中删除它。

BTW. if you have removed the /web behavior by some htaccess you should also remove it in the variables.