I am very new to Yii, so please bear with me here. It is my understanding that the preferred way to implement an administration section is to make an "admin" module. This much I understand. I also have used the Crud generator to make my administration section work and have themed it as well. My question is - How do we REUSE the models that are present in the admin module?
As a simple example, let’s say the administrator can register new users from within the admin module (Admin module, User model). How do we then reuse that User model on the front-end to allow users to register themselves? I am sure it’s possible, but I am having a bit of trouble figuring out the best way to achieve this effect.
I think the "right" way is to set up the model under protected/models and then use that model from the admin module (Or perhaps extend the base User model to add admin-specific methods).
Or am I misunderstanding things entirely, and an admin module is NOT the preferred way to set things up?
After playing with this for an hour or so, I see two logical solutions.
Make admin subdirectory under controllers. All admin CRUD operations will be housed here. Make one single user model class under models.
Make admin module. Make one single user model class under models. Admin operations will be inside the admin module, and will use the user model located in the app root under models.
What are the benefits to each? Which method do you prefer and why? Is there a better way than what I’ve come up with?
Second solution is good. If you have controller/action pairs like "post/create", you can do:
instead of something like:
Also having one model is fine. Actually the user model belongs to the main application, just like the admin module. If you have a model which belongs ONLY to the admin module (like a form model), you can put it under protected/modules/admin/models.
Thanks for the explanation. So a module is definitely the way to go here. Now the question is (I’m not at the office or I would test this myself) - How do I instantiate and use a model that belongs to the main app from a module?
IE I have protected/modules/admin/PostController.php and I have protected/models/User.php - Is it really as simple as $model = new User; from within the admin module? If that is all it really takes, what happens if (By error, in the future possibly) a new User model is created in the admin module? Then what happens when I try to instantiate the model class?
*I apologize for formatting errors if there are any. Typing from a phone…
Yes Yii will autoload the model when you access it from within a module. The module is part of the actual application (CWebApplication instance). Since the config for the main application will load first, the first model folder you define (import through config) has precedence I guess. Means if you have the same models under:
the first folder has precedence.