Search code examples
phpcodeignitercontrollereditingverification

Having an "edit" controller to deal with user editing? Does this design make sense?


Here is the flow:

  1. User creates a text based post.

  2. User edits a text based post (an edit page with the post info is displayed)

  3. User submits the changes to the post (a request sent to the post controller)

Now, if I have MULTIPLE types of posts, I have to check in steps 2 and 3 that the user is indeed updating the RIGHT type of post because someone could very well alter the URL to edit a post of type A when it's really of type B. This leads to a lot of redundant code, such as ...

if(user is indeed the editor && the post type is correct) show the edit page   

I think it would make a lot of sense to have an EDIT controller that does all the verification needed in the constructor (or maybe a base class?), and then calls the method. Have you encountered similar issues like this - and if not, does this make any design sense?


Solution

  • CodeIgniter is an MVC. That means that your controllers serve as an intermediate between your models (your data), and your view (front-end). "Edit" is an action that you do to objects, like data. Data objects should be organized within a controller, which calls the actual edit functions from the model.

    I'm assuming you have a Post controller. At its core, it should have basic CRUD functions, like adding and editing posts. It should look something like this:

    class Post extends CI_Controller
    {
        function __construct()
        {
            parent::__construct();
        }
    
        function index()
        {
            // List all posts, perhaps?
        }
    
        function add()
        {
            // Add a post
        }
    
        function edit($post_id)
        {
            // Edit a post
        }
    
        function view($post_id)
        {
            // View a post
        }
    
    }
    

    That will give you the following pages:

    Checking for user permissions is its own chapter. If you are using a library like Tank Auth, you can check permissions like so:

    if ($this->tank_auth->is_logged_in()) {
        // Do stuff
    }
    

    That should go at the beginning of each function - or in the __construct(), if you want to DRY it up completely.

    Good luck.