php - Why do we need to check if user is instance of UserInterface -


i've noticed in fosuserbundle controllers (profilecontroller) check if $user instance of userinteface

$user = $this->getuser(); if (!is_object($user) || !$user instanceof userinterface) {     throw new accessdeniedexception('this user not have access section.'); } 

is enough check if (!is_object($user))?

if user entity extends fos\userbundle\model\user, in case $user not instance of userinterface?

yes if code isn't meant open-sourced otherwise no.

not checking object's instance doesn't insure object returned method getuser() have methods expecting (example: getusername()).

if @ getuser() method controller.php not return user object. in fact, set symfony2 firewall in way getuser() return different object of different instance.

admitting have interface userinterface defines getusername().

in following code, our user object not implement userinterface.

$user = $this->getuser(); if (!is_object($user)) {     $user->getusername(); } 

this code throw error because getusername() not exist on object, instead code should have been following:

$user = $this->getuser(); if (!is_object($user) || !$user instanceof userinterface) {     $user->getusername(); } 

if user object not implement proper interface code won't error out because won't executed.

avoid checking object following

$user = $this->getuser(); if (!is_object($user) || !$user instanceof user) {     $user->getroles(); } 

if extends user object if statement won't executed anymore because $user not instance of user extendeduser though has methods need.

the other advantage of using interfaces can implement multiple interfaces on object.

class implements c {}  class b extends implements c, d {}  interface c {}  interface d {}  $na = new a(); $nb = new b();  $na instanceof a; // true - instance of $na instanceof b; // false - pretty obvious, no relationship b $na instanceof c; // true - implements c $na instanceof d; // false - not implement d  $nb instanceof a; // false - b not instance of $nb instanceof b; // true - instance of b $nb instanceof c; // true - implements c, that's key:                   //        both , b implements c b not                   //        instance of a. $nb instanceof d; // true - implements d 

tldr; interfaces great way set expectations , avoid major headaches.

when read through code can identify type of objects passed around. if changes code either show meaningful error or degrade gracefully (in case, user denied access).


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -