What are some common pitfalls to avoid when working with Models and Controllers in PHP frameworks, and how can these be addressed to improve code maintainability and flexibility?

Common pitfalls when working with Models and Controllers in PHP frameworks include tight coupling between the two, lack of separation of concerns, and excessive logic in controllers. To address these issues, it is important to follow the MVC design pattern, use dependency injection to decouple components, and keep controllers lightweight by moving business logic to the model layer.

// Example of using dependency injection to decouple Model and Controller

// Model
class UserModel {
    private $db;

    public function __construct(Database $db) {
        $this->db = $db;
    }

    public function getUserById($id) {
        // Query database using $this->db
    }
}

// Controller
class UserController {
    private $userModel;

    public function __construct(UserModel $userModel) {
        $this->userModel = $userModel;
    }

    public function getUser($id) {
        $user = $this->userModel->getUserById($id);
        // Process user data and return response
    }
}