lithium\data\Model::finder()

public static method

Sets or gets a custom finder by name. The finder definition can be an array of default query options, or an anonymous functions that accepts an array of query options, and a function to continue. To get a finder specify just the name.

In this example we define and use 'published' finder to quickly retrieve all published posts.

Posts::finder('published', [
    'conditions' => ['is_published' => true]
]);

Posts::find('published');

Here we define the same finder using an anonymous function which gives us more control over query modification.

Posts::finder('published', function($params, $next) {
    $params['options']['conditions']['is_published'] = true;

    // Perform modifications before executing the query...
    $result = $next($params);
    // ... or after it has executed.

    return $result;
});

When using finder array definitions the option array is recursivly merged (using Set::merge()) with additional options specified on the Model::find() call. Options specificed on the find will overwrite options specified in the finder.

Array finder definitions are normalized here, so that it can be relied upon that defined finders are always anonymous functions.

Parameters

  • string $name

    The finder name, e.g. 'first'.

  • string|callable|null $finder

    The finder definition.

Returns

callable|void

Returns finder definition if querying, or void if setting.

Source

	public static function finder($name, $finder = null) {
		$self = static::object();

		if ($finder === null) {
			return isset($self->_finders[$name]) ? $self->_finders[$name] : null;
		}
		if (is_array($finder)) {
			$finder = function($params, $next) use ($finder) {
				$params['options'] = Set::merge($params['options'], $finder);
				return $next($params);
			};
		}
		$self->_finders[$name] = $finder;
	}