eloquent.php 10.1 KB
Newer Older
1 2
<?php namespace System\DB;

3
use System\Str;
4
use System\Config;
5 6
use System\Inflector;

7 8 9 10 11 12 13 14 15 16
abstract class Eloquent {

	/**
	 * Indicates if the model exists in the database.
	 *
	 * @var bool
	 */
	public $exists = false;

	/**
17 18 19
	 * The model's attributes. 
	 *
	 * Typically, a model has an attribute for each column on the table.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
	 *
	 * @var array
	 */
	public $attributes = array();

	/**
	 * The model's dirty attributes.
	 *
	 * @var array
	 */
	public $dirty = array();

	/**
	 * The model's ignored attributes.
	 *
35 36
	 * Ignored attributes will not be saved to the database, and are
	 * primarily used to hold relationships.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
	 *
	 * @var array
	 */
	public $ignore = array();

	/**
	 * The relationships that should be eagerly loaded.
	 *
	 * @var array
	 */
	public $includes = array();

	/**
	 * The relationship type the model is currently resolving.
	 *
	 * @var string
	 */
	public $relating;

	/**
	 * The foreign key of the "relating" relationship.
	 *
	 * @var string
	 */
	public $relating_key;

	/**
64 65 66
	 * The table name of the model being resolved. 
	 *
	 * This is used during many-to-many eager loading.
67 68 69 70 71 72 73 74 75 76 77 78 79
	 *
	 * @var string
	 */
	public $relating_table;

	/**
	 * The model query instance.
	 *
	 * @var Query
	 */
	public $query;

	/**
80 81 82 83 84 85 86 87 88 89 90 91 92 93
	 * Create a new Eloquent model instance.
	 *
	 * @param  array  $attributes
	 * @return void
	 */
	public function __construct($attributes = array())
	{
		foreach ($attributes as $key => $value)
		{
			$this->$key = $value;
		}
	}

	/**
94 95 96 97 98 99 100 101 102 103 104 105
	 * Get the table name for a model.
	 *
	 * @param  string  $class
	 * @return string
	 */
	public static function table($class)
	{
		if (property_exists($class, 'table'))
		{
			return $class::$table;
		}

106
		return strtolower(Inflector::plural($class));
107 108 109 110 111 112 113 114 115 116 117
	}

	/**
	 * Factory for creating new Eloquent model instances.
	 *
	 * @param  string  $class
	 * @return object
	 */
	public static function make($class)
	{
		$model = new $class;
118

119 120
		// Since this method is only used for instantiating/ models for querying
		// purposes, we will go ahead and set the Query instance on the model.
121 122 123 124 125 126
		$model->query = Query::table(static::table($class));

		return $model;
	}

	/**
127 128 129 130 131 132 133
	 * Create a new model instance and set the relationships
	 * that should be eagerly loaded.
	 *
	 * @return mixed
	 */
	public static function with()
	{
134
		$model = static::make(get_called_class());
135 136 137 138 139 140 141 142 143 144 145 146 147
		$model->includes = func_get_args();

		return $model;
	}

	/**
	 * Get a model by the primary key.
	 *
	 * @param  int  $id
	 * @return mixed
	 */
	public static function find($id)
	{
148
		return static::make(get_called_class())->where('id', '=', $id)->first();
149 150 151 152 153 154 155 156 157
	}

	/**
	 * Get an array of models from the database.
	 *
	 * @return array
	 */
	private function _get()
	{
158
		return Eloquent\Hydrator::hydrate($this);
159 160 161 162 163 164 165 166 167
	}

	/**
	 * Get the first model result
	 *
	 * @return mixed
	 */
	private function _first()
	{
168
		return (count($results = Eloquent\Hydrator::hydrate($this->take(1))) > 0) ? reset($results) : null;
169 170 171 172 173 174
	}

	/**
	 * Retrieve the query for a 1:1 relationship.
	 *
	 * @param  string  $model
175
	 * @param  string  $foreign_key
176 177
	 * @return mixed
	 */
178
	public function has_one($model, $foreign_key = null)
179
	{
180 181
		$this->relating = __FUNCTION__;
		return $this->has_one_or_many($model, $foreign_key);
182 183 184 185 186 187
	}

	/**
	 * Retrieve the query for a 1:* relationship.
	 *
	 * @param  string  $model
188
	 * @param  string  $foreign_key
189 190
	 * @return mixed
	 */
191
	public function has_many($model, $foreign_key = null)
192
	{
193 194 195 196 197 198 199 200 201 202 203 204 205
		$this->relating = __FUNCTION__;
		return $this->has_one_or_many($model, $foreign_key);
	}

	/**
	 * Retrieve the query for a 1:1 or 1:* relationship.
	 *
	 * @param  string  $model
	 * @param  string  $foreign_key
	 * @return mixed
	 */
	private function has_one_or_many($model, $foreign_key)
	{
206 207 208
		// The default foreign key for has one and has many relationships is the name
		// of the model with an appended _id. For example, the foreign key for a
		// User model would be user_id. Photo would be photo_id, etc.
209
		$this->relating_key = (is_null($foreign_key)) ? strtolower(get_class($this)).'_id' : $foreign_key;
210 211

		return static::make($model)->where($this->relating_key, '=', $this->id);
212 213 214 215 216 217
	}

	/**
	 * Retrieve the query for a 1:1 belonging relationship.
	 *
	 * @param  string  $model
218
	 * @param  string  $foreign_key
219 220
	 * @return mixed
	 */
221
	public function belongs_to($model, $foreign_key = null)
222
	{
223 224 225 226 227 228 229 230
		$this->relating = __FUNCTION__;

		if ( ! is_null($foreign_key))
		{
			$this->relating_key = $foreign_key;
		}
		else
		{
231 232 233
			// The default foreign key for belonging relationships is the name of the
			// relationship method name with _id. So, if a model has a "manager" method
			// returning a belongs_to relationship, the key would be manager_id.
234
			list(, $caller) = debug_backtrace(false);
235

236 237 238 239
			$this->relating_key = $caller['function'].'_id';
		}

		return static::make($model)->where('id', '=', $this->attributes[$this->relating_key]);
240 241 242 243 244 245
	}

	/**
	 * Retrieve the query for a *:* relationship.
	 *
	 * @param  string  $model
246
	 * @param  string  $table
247 248
	 * @return mixed
	 */
249
	public function has_and_belongs_to_many($model, $table = null)
250
	{
251 252 253 254 255 256 257 258
		$this->relating = __FUNCTION__;

		if ( ! is_null($table))
		{
			$this->relating_table = $table;
		}
		else
		{
259 260
			// By default, the intermediate table name is the plural names of the models
			// arranged alphabetically and concatenated with an underscore.
261 262
			$models = array(Inflector::plural($model), Inflector::plural(get_class($this)));

263 264
			sort($models);

265
			$this->relating_table = strtolower($models[0].'_'.$models[1]);
266 267
		}

268
		// The default foreign key for many-to-many relations is the name of the model with an appended _id.
269
		// This is the same convention as has_one and has_many.
270
		$this->relating_key = strtolower(get_class($this)).'_id';
271 272

		return static::make($model)
273
                               ->select(static::table($model).'.*')
274
                               ->join($this->relating_table, static::table($model).'.id', '=', $this->relating_table.'.'.strtolower($model).'_id')
275
                               ->where($this->relating_table.'.'.$this->relating_key, '=', $this->id);
276 277 278 279 280
	}

	/**
	 * Save the model to the database.
	 *
281
	 * @return bool
282 283 284
	 */
	public function save()
	{
285 286 287 288 289
		if ($this->exists and count($this->dirty) == 0)
		{
			return true;
		}

290 291
		$model = get_class($this);

292
		// Since the model was instantiated using "new", a query instance has not been set.
293 294 295 296 297 298 299 300 301 302 303 304 305
		$this->query = Query::table(static::table($model));

		// Set the creation and update timestamps.
		if (property_exists($model, 'timestamps') and $model::$timestamps)
		{
			$this->updated_at = date('Y-m-d H:i:s');

			if ( ! $this->exists)
			{
				$this->created_at = $this->updated_at;
			}
		}

306 307
		// If the model already exists in the database, we only need to update it.
		// Otherwise, we'll insert the model into the database.
308 309 310 311 312 313 314 315 316 317
		if ($this->exists)
		{
			$result = $this->query->where('id', '=', $this->attributes['id'])->update($this->dirty) == 1;
		}
		else
		{
			$this->attributes['id'] = $this->query->insert_get_id($this->attributes);

			$result = $this->exists = is_numeric($this->id);
		}		
318 319 320 321 322 323 324 325

		$this->dirty = array();

		return $result;
	}

	/**
	 * Delete a model from the database.
326 327 328
	 *
	 * @param  int  $id
	 * @return int
329 330 331 332 333
	 */
	public function delete($id = null)
	{
		if ($this->exists)
		{
334
			return Query::table(static::table(get_class($this)))->delete($this->id);
335 336
		}

337
		return 0;
338 339 340 341 342 343 344
	}

	/**
	 * Magic method for retrieving model attributes.
	 */
	public function __get($key)
	{
345 346
		// Check the ignored attributes first. These attributes hold all of the
		// loaded relationships for the model.
347 348 349 350 351
		if (array_key_exists($key, $this->ignore))
		{
			return $this->ignore[$key];
		}

352 353
		// Is the attribute actually a relationship method? If it is, return the
		// models for the relationship.
354 355 356 357 358
		if (method_exists($this, $key))
		{
			$model = $this->$key();

			return ($this->relating == 'has_one' or $this->relating == 'belongs_to')
359 360
                                                                  ? $this->ignore[$key] = $model->first()
                                                                  : $this->ignore[$key] = $model->get();
361 362 363 364 365 366 367 368 369 370
		}

		return (array_key_exists($key, $this->attributes)) ? $this->attributes[$key] : null;
	}

	/**
	 * Magic Method for setting model attributes.
	 */
	public function __set($key, $value)
	{
371
		// If the key is a relationship, add it to the ignored attributes.
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
		if (method_exists($this, $key))
		{
			$this->ignore[$key] = $value;
		}
		else
		{
			$this->attributes[$key] = $value;
			$this->dirty[$key] = $value;
		}
	}

	/**
	 * Magic Method for determining if a model attribute is set.
	 */
	public function __isset($key)
	{
		return (array_key_exists($key, $this->attributes) or array_key_exists($key, $this->ignore));
	}

	/**
	 * Magic Method for unsetting model attributes.
	 */
	public function __unset($key)
	{
		unset($this->attributes[$key]);
		unset($this->ignore[$key]);
		unset($this->dirty[$key]);
	}

	/**
	 * Magic Method for handling dynamic method calls.
	 */
	public function __call($method, $parameters)
	{
		if ($method == 'get')
		{
			return $this->_get();
		}

		if ($method == 'first')
		{
			return $this->_first();
		}

		if (in_array($method, array('count', 'sum', 'min', 'max', 'avg')))
		{
			return call_user_func_array(array($this->query, $method), $parameters);
		}

421 422
		// Pass the method to the query instance. This allows the chaining of methods
		// from the query builder, providing a nice, convenient API.
423 424 425 426 427 428 429 430 431 432
		call_user_func_array(array($this->query, $method), $parameters);

		return $this;
	}

	/**
	 * Magic Method for handling dynamic static method calls.
	 */
	public static function __callStatic($method, $parameters)
	{
433
		$model = static::make(get_called_class());
434

Taylor Otwell committed
435
		if ($method == 'get' or $method == 'all')
436 437 438 439 440 441 442 443 444 445 446 447 448 449
		{
			return $model->_get();
		}

		if ($method == 'first')
		{
			return $model->_first();
		}

		if (in_array($method, array('count', 'sum', 'min', 'max', 'avg')))
		{
			return call_user_func_array(array($model->query, $method), $parameters);
		}

450 451
		// Pass the method to the query instance. This allows the chaining of methods
		// from the query builder, providing a nice, convenient API.
452 453 454 455 456 457
		call_user_func_array(array($model->query, $method), $parameters);

		return $model;
	}

}