I've recently started using Yii 2
and I'm having some issues with the layout file with getting the below error:
Call to undefined method Yii::app()
This is my layout file:
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $content string */
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?=Yii::$app->language?>">
<head>
<title><?=Html::encode($this->title)?></title>
<meta charset="<?=Yii::$app->charset?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?=Html::csrfMetaTags()?>
<link href="<?=Yii::app()->request->baseUrl;?>/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="<?=Yii::app()->request->baseUrl;?>/css/custom.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="<?=Yii::app()->request->baseUrl;?>/js/bootstrap.min.js"></script>
<script type="text/javascript" src="<?=Yii::app()->request->baseUrl;?>/js/scripts.js"></script>
<!--[if lte IE 8]>
<script src="<?=Yii::app()->request->baseUrl;?>/js/html5shiv.min.js"></script>
<script src="<?=Yii::app()->request->baseUrl;?>/js/respond.min.js"></script>
<![endif]-->
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<?=$content?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
When I use Yii::$app
I get no issues, but if I use Yii::app()
then I get that error.
I started using Yii::app()
in some places as I was reading around and was told you should use the below to make sure to include absolute path names within views:
Yii::app()->request->baseUrl
...and to include jQuery use:
Yii::app()->clientScript->registerCoreScript("jquery");
However when I do anything with app()
I get the above error.
I tried replacing app()
with $app
; the page loaded fine but there was a blank value in Yii::$app->request->baseUrl
.
What am I doing wrong here!?
In Yii 2, $app
is a property of Yii, not a method, so you should use Yii::$app->blah
.
Source
Try this: Yii::$app->request->baseUrl;
Yii::$app
is the static var for the Yii2 Application class, 'yii\web\Application'. It refers to an an instance of the Yii Application class. Since the Request
class is a configured as an application component by default you have access to the tons of useful properties: Request Class Reference
Yii2 also comes with a bunch of helper classes that do many of the same things: BaseUrl Helper
Usage is: Url::base();
...be sure to use the namespace by placing use yii\helpers\Url;
at the top of your controller (below the main namespace).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With