Jump to content

Using MVC model with multiple objects possible?


jbonnett

Recommended Posts

Hi all,

I was just wondering is this possible what I'm trying to do?

Models can only store one object at a time...

I'm trying to access multiple objects via one model...

<?php

	class users extends Model {
		
		protected $username;
		protected $firstname;
		protected $secondname;
		protected $age;
		// There will be more here...
		
		public function __construct($id = NULL) {
			
			if($id != NULL) {
				
				$this->username = $sql->getUsername($id);
				$this->firstname = $sql->getFirstname($id);
				$this->secondname = $sql->getSecondname($id);
				$this->age = $sql->getAge($id);
				
			}
			
		}
		
		public function numOfUsers() {
			
			$num = $sql->countAllUsers($query);
			
			return $num;
			
		}
		
		public function getUsername() {
			
			return $this->username;
			
		}
		
		public function getFirstname() {
			
			return $this->firstname;
			
		}
		
		public function getSecondname() {
			
			return $this->secondname;
			
		}
		
		public function getAge() {
			
			return $this->age;
			
		}
		
	};
	
	class UsersView extends View {
		
		$users = new users();
		
		for($i = 0; $i < $users->numOfUsers(); $i++) {
		
			$user = new users($i);
			echo "Username: {$user->getUsername()}";
			echo "Username: {$user->getFirstname()}";
			echo "Username: {$user->getSecondname()}";
			echo "Username: {$user->getAge()}";
			
		}
		
	};

?>

Create a class that wraps your models:

 

class UserManager {
  private $userModel;
  private $fooModel;
  
  public function __construct(Users $userModel, Foos $fooModel) {
    $this->userModel = $userModel;
    $this->fooModel = $fooModel;
  }
   
  public function doX() {
    // do stuff
  }
}
Drop the usersView. It's a concept you are not yet ready to grasp and you don't need it, keep it simple.

 

Also your Model classes seem overly complex and incoherent. Keep it to a minimum and simple.

 

class UsersModel extends Model {
  public function find($id) {
    // ..
  }
  public function findByUsername($username) {
    // ..
  }
  public function save() {
    // ..
  }
  // other db operation methods
}
Your model classes should be specific to db operations, while the manager class should do the higher level stuff like for example registration while the model would actually write the user to the database.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.