2014-10-28 46 views
1

上引用或定义一次。我应该每次使用laravel Auth :: user使用Laravel 4及其Auth功能在页面

假设我想检查登录ID是否与博客创建者ID匹配。

if (Auth::user()->id == $blog->blogOwnerID) 
{ 
    // do something 
} 

工作正常,但我需要检查页面中的各个位置。

另一种选择是将用户ID和博客创建者ID设置为变量以便于使用。

// at start of page 
$blogOwnerID = $blog->blogOwnerID; 
if (Auth::check()) 
{ 
    $userID = Auth::user()->id; 
} 

现在林不知道是否会有,除非引用它检查反正变量时不调用函数每次,任何的性能提升。

只是寻找正确的做事方式:)

克雷格。

回答

1

是的,如果不一次又一次调用函数,会有一个(小)性能优势。它是非常小的,所以它真的归结为更可读和更喜欢什么。

我会做这样的:

$userId = Auth::check() ? Auth::user()->id : false; 
$blogOwnerID = $blog->blogOwnerID; 

// do my checks 
if ($blogOwnerID === $userId) { 
    // do something 
} 

确保您使用===这样你就不会得到误报如果$blog->blogOwnerID是0

+0

感谢,非常肯定,在性能止跌的通知不是主要的。我可以问这种类型的if语句的名称吗?已经看到它使用,但从来不知道它的所谓或更多的信息。 – Lovelock 2014-10-28 23:42:51

+1

你的意思是'Auth :: check()? Auth :: user() - > id:false;'?如果 – lukasgeiter 2014-10-28 23:48:23

+1

被称为*速记*它被称为三元运算符或速记 - 如果 - http://www.tuxradar.com/practicalphp/3/12/4 – 2014-10-28 23:49:56