lithium\data\Model::__callStatic()

public static method

Enables magic finders. These provide some syntactic-sugar which allows to i.e. use Model::all() instead of Model::find('all').

// Retrieves post with id `23` using the `'first'` finder.
Posts::first(['conditions' => ['id' => 23]]);
Posts::findById(23);
Posts::findById(23);

// All posts that have a trueish `is_published` field.
Posts::all(['conditions' => ['is_published' => true]]);
Posts::findAll(['conditions' => ['is_published' => true]]);
Posts::findAllByIsPublshed(true)

// Counts all posts.
Posts::count()

Parameters

  • string $method

    Method name caught by __callStatic().

  • array $params

    Arguments given to the above $method call.

Returns

mixed

Results of dispatched Model::find() call.

Source

	public static function __callStatic($method, $params) {
		$self = static::object();

		if (isset($self->_finders[$method])) {
			if (count($params) === 2 && is_array($params[1])) {
				$params = [$params[1] + [$method => $params[0]]];
			}
			if ($params && !is_array($params[0])) {
				$params[0] = ['conditions' => static::key($params[0])];
			}
			return $self::find($method, $params ? $params[0] : []);
		}
		preg_match('/^findBy(?P<field>\w+)$|^find(?P<type>\w+)By(?P<fields>\w+)$/', $method, $args);

		if (!$args) {
			$message = "Method `%s` not defined or handled in class `%s`.";
			throw new BadMethodCallException(sprintf($message, $method, get_class($self)));
		}

		$field = Inflector::underscore($args['field'] ? $args['field'] : $args['fields']);
		$type = isset($args['type']) ? $args['type'] : 'first';
		$type[0] = strtolower($type[0]);

		$conditions = [$field => array_shift($params)];
		$params = (isset($params[0]) && count($params) === 1) ? $params[0] : $params;
		return $self::find($type, compact('conditions') + $params);
	}