lithium\data\source\Database::_init()

protected method

Initializer. Initializes properties like Database::$_strategies because closures cannot be created within the class definition.

Source

	protected function _init() {
		parent::_init();

		if (!$this->_config['database']) {
			throw new ConfigException('No database configured.');
		}

		$formatters = $this->_formatters();

		foreach ($this->_columns as $type => $column) {
			if (isset($formatters[$type])) {
				$this->_columns[$type]['formatter'] = $formatters[$type];
			}
		}

		$this->_strings += [
			'read' => 'SELECT {:fields} FROM {:source} {:alias} {:joins} {:conditions} {:group} ' .
			          '{:having} {:order} {:limit};{:comment}'
		];

		$this->_strategies += [
			'joined' => function($model, $context) {

				$with = $context->with();

				$strategy = function($me, $model, $tree, $path, $from, &$deps) use ($context, $with) {
					foreach ($tree as $name => $childs) {
						if (!$rel = $model::relations($name)) {
							throw new QueryException("Model relationship `{$name}` not found.");
						}

						$constraints = [];
						$alias = $name;
						$relPath = $path ? $path . '.' . $name : $name;
						if (isset($with[$relPath])) {
							list($unallowed, $allowed) = Set::slice($with[$relPath], [
								'alias',
								'constraints'
							]);
							if ($unallowed) {
								$message = "Only `'alias'` and `'constraints'` are allowed in ";
								$message .= "`'with'` using the `'joined'` strategy.";
								throw new QueryException($message);
							}
							extract($with[$relPath]);
						}
						$to = $context->alias($alias, $relPath);

						$deps[$to] = $deps[$from];
						$deps[$to][] = $from;

						if ($context->relationships($relPath) === null) {
							$context->relationships($relPath, [
								'type' => $rel->type(),
								'model' => $rel->to(),
								'fieldName' => $rel->fieldName(),
								'alias' => $to
							]);
							$this->join($context, $rel, $from, $to, $constraints);
						}

						if (!empty($childs)) {
							$me($me, $rel->to(), $childs, $relPath, $to, $deps);
						}
					}
				};

				$tree = Set::expand(array_fill_keys(array_keys($with), false));
				$alias = $context->alias();
				$deps = [$alias => []];
				$strategy($strategy, $model, $tree, '', $alias, $deps);

				$models = $context->models();
				foreach ($context->fields() as $field) {
					if (!is_string($field)) {
						continue;
					}
					list($alias, $field) = $this->_splitFieldname($field);
					$alias = $alias ?: $field;
					if ($alias && isset($models[$alias])) {
						foreach ($deps[$alias] as $depAlias) {
							$depModel = $models[$depAlias];
							$context->fields([$depAlias => (array) $depModel::meta('key')]);
						}
					}
				}
				$context->with([]);
			},
			'nested' => function($model, $context) {}
		];
	}