Yii::$app->user->identity is using my model function


I just installed Intelephense and it was marking a function as undefined. It is weird because it works.

I have a model that extends the interface from Identity. In this model, I have a function called ‘isDealer’.

If I execute Yii::$app->user->identity->isDealer(), it works. But Intelephense marks it as undefined because Yii::$app->user->identity is actually an interphase. Why can I use isDealer() if Yii::$app->user->identity is not the Model I created? I thought it was the model at first. But I’m not so sure anymore. IsDealer() is not defined in identity, but it is defined in my model that extends from it.

Any help is appreciated.

Since the identity is “marked” as interface, the Intelephense understands that only the methods defined by the interface are valid.

When you create a new method, like the isDealer, it won’t know that it exists, because it only looks to the interface. That’s way it gives you an error. And because the class you are using have this method, it will work.

If you follow some patterns, like SOLID, you see that creating methods in those classes that are not defined by the interface is not a good thing.

In case you need to change your custom class, you might get errors regarding that extra method.

1 Like

Thanks for your reply! If creating a method (following some patterns) in those classes is not a good thing, is it recommended to define the method in the interface? The interface is given by yii2, I think I should not modify it. Otherwise, if I need a method, how should I do it?

The important part is that you need to guarantee that upon calling that interface, the method should exist. Here are some different ways of solving this:

  • Have a Service (or some on that line) with a method to check if some user have some role. This will provide better reuse, since you can implement the role validation once and use it for multiple types of roles.
  • Leave Intelephense be, just make sure you will always use that implementation of the extended IdentityInterface you created.
  • Create another interface with the method isDealer and (before calling the method on the variable) make sure your variable is an implementation of that interface.

As I’ve said, depends on the pattern you are following, especially since PHP allows you to implement multiple Interfaces.

1 Like