Skip to content

Auto_Modeler 1.5 Release

I’ve released version 1.5 of my Auto_Modeler Kohana module today. This is a pretty big release. It provides built in support for in-model data validation. Here’s a list of all the changes:

Auto_Modeler:

  • Added support for in-model validation
  • Added a $rules member array variable (an array of rule arrays)
  • Added a $callbacks member array variable
  • Added a ‘fetch_some’ method to search for specific database rows with a where() array
  • Added comments =)

Auto_Modeler_ORM:

  • Fixed some bugs with many to many relationship setting
  • Added one to many support in find_related()
  • Added one to many support in find_parent()
  • Added one to many support in delete()
  • Added has_attribute()

The big change is the built in validation. Here’s an example of how I use it.
First, my model:

class Asset_Model extends Auto_Modeler_ORM {

	// Database table name
	protected $table_name = 'assets';

	// Database fields and default values
	protected $data = array('id'       =>  '',
	                                 'title'    => '');

	protected $has_many = array('files', 'countries');
	protected $belongs_to = array('categories');

	protected $rules = array('title' => array('required'),
	                         'description' => array('required'));

	// Overloading delete() to delete the physical file as well.
	public function delete()
	{
		// Delete all the files
		$files = Auto_Modeler_ORM::factory('file')->fetch_some(array('asset_id' => $this->data['id']));
		echo Kohana::debug($files);
		foreach ($files as $file)
		{
			$dest_dir = APPPATH.'views/assets/'.substr($file->filename, 0, 1).'/';
			$uploadfile = str_replace(' ', '_', $dest_dir.$file->filename);
			unlink($uploadfile);
		}

		parent::delete();
	}

	protected function check_country(Validation &$validation)
	{
		$validation->add_rules('country', 'required');
	}

	protected function check_category(Validation &$validation)
	{
		$validation->add_rules('category', 'required');
	}

	protected function check_file(Validation &$validation)
	{
		$validation->add_callbacks('file', array($this, 'validate_file_upload'));
	}

	public function validate_file_upload(Validation &$validation, $input)
	{
		if (isset($_FILES) AND $_FILES[$input]['error'])
			$validation->add_error($input, 'no_file');
		else if (count($this->db->getwhere('files', array('filename' => $_FILES[$input]['name']))))
			$validation->add_error($input, 'duplicate_filename');
	}
}

Now here’s the insert() method of my controller:

	public function insert()
	{
		if ( ! ($this->auth->logged_in('admin') OR $this->auth->logged_in('publisher')))
			Event::run('system.404');

		$asset = new Asset_Model();

		if ( ! $_POST)
		{
			$region = new Region_Model();
			$this->template->body = new View('asset/insert');
			$this->template->body->regions = $region->fetch_all();
			$this->template->body->errors = '';
		}
		else
		{
			$post = $this->input->post();

			$asset->title = $post['title'];
			$asset->description = $post['description'];

			try
			{
				// Save the asset
				$asset->save(
					array('country' => $this->input->post('country', array()), 'category' => $this->input->post('category', array())), // Additional data to validate with the form
					array('check_country', 'check_category', 'check_file') // Model callbacks to run
				);

				// Then upload the file
				$dest_dir = APPPATH.'views/assets/'.substr($_FILES['file']['name'], 0, 1).'/';
				$uploadfile = str_replace(' ', '_', $dest_dir.$_FILES['file']['name']);

				! is_dir($dest_dir) AND mkdir($dest_dir, 0777, TRUE);
				move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);

				foreach ($post['country'] as $country)
					$asset->countries = $country;

				$asset->category_id = $post['category'];

				$file = new File_Model();
				$file->filename = str_replace(' ', '_', $_FILES['file']['name']);
				$file->asset_id = $asset->id;
				$file->timestamp = time();
				$file->save();

				url::redirect('');
			}
			catch (Kohana_User_Exception $e)
			{
				$region = new Region_Model();
				$this->template->body = new View('asset/insert');
				$this->template->body->regions = $region->fetch_all();
				$this->template->body->errors = $e;
				$this->template->body->set($post);
			}
		}
	}

The important part of this block of code is in the try/catch block. The model does all the validation internally. So when it save()s, it will try and validate it’s internal data. If it fails, it will throw an exception that includes the error messages (this comes from views/form_errors.php).

The second new part of this code is the extra parameters in the save() method. This form has external requirements seperate from the assets table that are required (country and category). A file upload is also required.

Since this data has nothing inherintly to do with the asset model or database table, we pass them as callbacks. The model has callback methods to check the external data. So we pass the extra data in with the first parameter to save(), and the second parameter is the callbacks to run in addition to the built in validation.

If the save() succeeds, we continue our insert procedure, otherwise we skip to the catch{} block and display the form again with the invalida data and errors.

Post a Comment

You must be logged in to post a comment.
  • chicago bears 61
  • chicago bears expo 2011
  • lifted
  • connecticut 30 news
  • hp support error 1005
  • recruiting
  • impressions
  • turning
  • cspan washington correspondents dinner 2011
  • chad ochocinco yesterday
  • largest
  • hp support contact number
  • bengals insider
  • mtv 25 lame
  • hp support monitors
  • vince young redskins
  • searchbugsearch engines
  • battleship 1967
  • search 2.0
  • search engines for jobs
  • hp support 6310hp support 7200
  • la ink jabberwocky
  • chad ochocinco quotes video
  • new england patriots jake locker
  • zara phillips wedding date
  • c span 4 to 5
  • vince young stats
  • fees
  • bea exhibitors
  • cycles
  • bangles eternal flame mp3bengals forum
  • zara phillips baby
  • quatro
  • bea test
  • tea party manifesto
  • countertops
  • search in vi
  • tea party agenda
  • randy moss future
  • bea 71 series staples
  • randy moss university
  • strait
  • search comcast net
  • crew
  • connecticut 97.7connecticut attorney general
  • chicago bears number 17
  • randy moss college
  • connecticut transit
  • mtv jams
  • vince young 2008
  • vina
  • vince young 6
  • chicago bears 2009 roster
  • vince young yahoo stats
  • cloverfield
  • chad ochocinco nascar
  • bea 4603
  • battleship egg hunt
  • adirondack
  • battleship layout
  • la ink season 5 premiere
  • mtv executivesmtv fantasy factory
  • randy moss mix
  • 1855
  • sasquatch
  • oval
  • hacks
  • mtv youtube channel
  • battleship galactica
  • new england patriots 98.5
  • la ink book an appointment
  • hp support 6930p
  • freida pinto 1995
  • chad ochocinco age
  • search jail inmates
  • search engines other than google
  • menthol
  • beagle
  • greg olsen dustin keller
  • dist 91
  • chicago bears media relations
  • chicago bears garter
  • experiment
  • tactical
  • tea party birthday
  • zara phillips school
  • connecticut juvenile training schoolconnecticut kids
  • bea diy
  • router
  • hp support number united states
  • di's hallmark
  • la ink cast
  • 4pm cspancspan area 51cspan 90.1
  • tea party hats
  • eyelashes
  • chad ochocinco to patriots
  • nutrisystem
  • battleship ipad
  • walkthrough
  • bengals images
  • c span yesterdayc span zelaya
  • rowe
  • chicago bears training camp
  • vince young yahoo stats
  • connecticut quarry
  • chad ochocinco sisterchad ochocinco twitter
  • entry
  • search engines before google
  • cspan streaming
  • usaa
  • search engines non tracking
  • chicago bears tickets
  • dis lyrics
  • diagnostics
  • mite
  • freida pinto jeansfreida pinto kissing
  • randy moss height
  • battleship kirishima
  • tea party table settings
  • search engines usage statistics 2010
  • hp support chat
  • tea party medicare
  • search 32
  • la ink youtube pixie
  • vince young uncle rico
  • dis poem
  • battleship yamato wreck
  • chicago bears gifts
  • chrome
  • glenn
  • chicago bears tattoos
  • connecticut lottery
  • bengals 09 record
  • search engines 9
  • chicago bears 09 draft
  • freida pinto dev
  • vince young quiz
  • chicago bears 1985
  • bengals 09
  • peril
  • mtv website
  • connecticut limo
  • connecticut state parks
  • connecticut department of labor
  • zara phillips and the queen
  • vince young 10 11
  • search engines of the world
  • bea luna
  • wealth
  • la ink upcoming episodes
  • bea 00037
  • appartments
  • osiris
  • swivel
  • la ink ink
  • bengals for adoption
  • search 4
  • randy moss bio
  • search xml file
  • la ink bob tyrrell
  • bea 2011 map
  • connecticut 5th district
  • bengals qb situation
  • nights
  • search engines for jobs
  • crocs
  • chad ochocinco wedding date
  • dis tester
  • vince young 3rd 30
  • tea party 8 28 09
  • hp support error 1005
  • repeated
  • eyelids
  • connecticut airports
  • potentiometer
  • new england patriots rumors
  • new england patriots kim kardashian
  • battleship history
  • dis x
  • greg olsen boulder
  • travolta
  • vince young jersey texas
  • search engines and flash
  • dis v44