Yii Framework Forum: create short object - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

create short object

#1 User is offline   googoli 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 30-October 15

Posted 04 November 2017 - 08:38 AM

hi guys
i saw some one use app() instead of Yii::$app
How is this possible? and how to use it
0

#2 User is offline   Fabrizio Caldarelli 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 1,058
  • Joined: 21-March 13
  • Location:Rome, Italy

Posted 04 November 2017 - 10:08 AM

Yii::app() is for Yii1 and Yii::$app is for Yii2.
Yii2 by example: my book about Yii2
https://www.packtpub...nt/yii2-example
0

#3 User is offline   googoli 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 2
  • Joined: 30-October 15

Posted 04 November 2017 - 02:23 PM

Yes I know but i saw app()->user->id in yii2

Yii::$app convert to app()
0

#4 User is offline   alrazi 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,366
  • Joined: 08-August 12
  • Location:Durban, South Africa

Posted 05 November 2017 - 09:26 AM

its likely that app() function is defined by user to wrap Yii::$app which in return enable the following app()->user->id in yii2, where did you see it in craftcms?
0

#5 User is offline   umneeq 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 137
  • Joined: 10-October 11
  • Location:Russia

Posted 06 November 2017 - 05:43 PM

It is just a shortcut. I use lot of such procedural functions. Here is couple examples:
function set_flash($value, $key = 'success') {
    Yii::$app->session->setFlash($key, $value);
}
set_flash('cool');

function can($permissionName, $params = [], $allowCaching = true) {
    return Yii::$app->user->can($permissionName, $params, $allowCaching);
}
if(can('admin') && !is_role('moderator')) {

}

function assign_role($user_id, $role) {
    $auth = \Yii::$app->authManager;
    $authorRole = $auth->getRole($role);
    $auth->assign($authorRole, $user_id);
}
assign_role('admin');

function is_guest() {
    return Yii::$app->user->isGuest;
}
if(is_guest()){
    Yii::$app->user->loginRequired();
}

This functions included in index.php file so they can be accessed in whole project.
But app() instead of Yii::$app looks like for very lazy guy )
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users