问题
I have at least one model in my Yii project that will need to reference a particular user ID. In my SQL for the model I have something like CONSTRAINT FOREIGN KEY (user_id) REFERENCES User(id)
. I was going to go ahead and create a User model when I came across the docs for CUserIdentity. I have to admit I am confused. Is a CUserIdentity a user or a state associated with a particular user-case? I would like to use as much of the built-in Yii features as possible since they handle a lot of security-related issues from what I understand, and I am aware of the existence of some modules like srbac
that handle user authentication and registration management. Please guide me in the right direction. (Also at issue: what is the relationship between models and components?)
回答1:
First off, do go ahead and create a User
model, you will need it.
With that out of the way: CUserIdentity
represents the concept of "who the user is", while the User
model represents "information about a user of my application". CUserIdentity
is applicable in all cases where there is more than one kind of user (i.e. guest), while the User
model is only applicable when you are storing information about the users yourself. Admittedly, in most cases both will be applicable and this is what creates the confusion.
Usually, the relation between the two is that CUserIdentity
, in order to answer questions such as "who the user is", "is the user allowed to access this resource" etc. queries the User
model from the database to get the information it needs to answer these questions. This relationship between the two concepts is also documented in the definitive guide to Yii. After e.g. authenticating the user, it would expose some or all of the information on the User
model through its own properties (which you would have to define).
To give an example of a scenario where there would be no User
model, think about a website that lets you log in using your LDAP user account. When the CUserIdentity::authenticate
method is called, the component would authenticate the credentials against the LDAP server and after a successful authentication would again grab any other relevant information and expose it through its own properties.
来源:https://stackoverflow.com/questions/7458940/yii-cuseridentity-vs-a-user-model