I don’t know if this is a bug or a user error or user confusion. I’m using a CAccessRule expression, which is supposed to be a string. If I use a string like “1==1” or “1==2” it works as expected. But I want to base the expression upon a “role” property I added to user, as in
[tt]Yii::app()->user->role == 'admin'[/tt]
If I put that in a string, it doesn't work. The manual says I can use $user instead of Yii::app()->user, but when I do that (in a string), I get "Undefined variable: user". However if I do this:
[tt]'expression'=>isset(Yii::app()->user->role) && (Yii::app()->user->role == 'admin')[/tt]
it does work. Is this a bug or am I misunderstanding something?
I'm using Yii 1.0.6 with PHP 5.2.6 on Mac OS X Server 10.5.7. Results are consistent in Firefox 3.0.11 and Safari 4.0.
Thanks to anyone for their assistance and big kudos on Yii!
What is your expression using $user?
Sorry about that. I get the same response (undefined variable) whether I do:
[tt]'expression'=> $user == 'admin'[/tt]
[tt]'expression'=> "$user == 'admin'"[/tt]
And just to confirm, when the docs say it's a string, I assume that it's a string that gets eval'd, which is why 1==1 grants permission but 1==2 does not. Is that correct? Although in the usage of it that did work for me, it's evaluating immediately and assigning a boolean to expression.
And thanks for your help!
It should be
'expression'=>'isset($user->role) && $user->role==="admin"'
Okay, now I have no idea what I did wrong previously, because the code I just posted wasn't correct, obviously, but the code you recommended did work. Clearly my mistake somewhere.
Big thanks for your help and for the Yii Framework!
When you use 'expression'=> $user == 'admin', the expression actually gets the value of $user == 'admin'. And when you use 'expression'=> "$user == 'admin'", $user will be replaced with its value. In both cases, you should encounter a PHP error if $user is not defined.