不同用户类型的应用程序设计

I'm trying to figure out the best way to build an application with multiple user types (i.e. Admin, Vendor and Customer).

I'm using Symfony2 to develop the application. I have two options in mind:

  1. Have one controller and check for the user role and render the corresponding view for that role. (One controller, Multiple views)
  2. Have one view and check for the user role to render the corresponding piece. (One controller, one view)

The difference between the above two methods, that is think the first one will have views to be cleaner, without too much logic in it. But will lead to too much logic inside the controller.

If there any better way to think this out ?

I developed a site with Symfony2 and user roles. I didn't change entire pages depending on the role, but there were significant chunks that would change based on role. I went with option 2 and used the logic within the views, and that seemed to work well for me. Cheers

The way I do it is similar to your option 2 I am not sure how it works with symphony since I have my own custom framework but its similar in a way:

  1. Controller handles the logic and passes in the parameter to view about user, whether user is admin or has a specific permission
  2. View then renders specific parts of the code depending on this permission/role

Example Controller:

 $view = new View('PATH_TO_VIEW');

 $view->isAdmin = true;
 $view->canDropDatabase = true;

Example View:

 <div>
     <?php if ($this->isAdmin) : ?>
         *** Show some Admin Stuff ***
     <?php else : ?>
         *** Show Non-Admin Stuff ***
     <?php endif; ?>

     <?php if ($this->canDropDatabase) : ?>
         *** Well I hope you dont do this ***
     <?php endif; ?>
 </div>

The reason I like this approach is because if I need to update something I only deal with one file versus each view file for each role. Plus for the future if you add roles you need to add a new file while you can just add an extra elsif condition.

Personally I would go with option 1.

You can minimize the logic in controller by just passing the role of the user as a string/array to your twig template and use something like:

{% include role ~ 'header.html' %}

or in case of an array on which you need to do some checks/apply logic you can use a custom twig extension instead of logic in controllers

{% include roles|check_roles ~ 'header.html' %}

Alternatively you can create a service class and inject it in twig so you can use it's methods inside the view so that you keep your controllers clean and the concern of selecting view/partial for each role to be in one place only.