Skip to content

CakePHP2.x Snippets

dereuromark edited this page Nov 16, 2014 · 7 revisions

Useful snippets for CakePHP 2.x

Code

Routing pages to root level /my-page-slug and I18n

Assuming you are using the default 2.x PagesController - in Config/routes.php:

// Before:
//Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));

// After:
$pageRoutes = array(
	'imprint' => 'impressum'
);
$path = APP . 'View' . DS . 'Pages' . DS;
$Iterator = new DirectoryIterator($path);
foreach ($Iterator as $page) {
	if ($page->isDot()) {
		continue;
	}
	$page = substr($page, 0, -4);
	$routedPage = isset($pageRoutes[$page]) ? $pageRoutes[$page] : $page;
	Router::connect('/' . $routedPage, array('controller' => 'pages', 'action' => 'display', $page));
}

Model/Behavior afterFind()

afterFind can historically receive data in different ways. This is annoying to work with

/**
 * Unify array structure to make afterFind code easier to write and maintain.
 *
 * @see https://github.com/cakephp/cakephp/issues/2529
 *
 * @param mixed $results
 * @param bool $primary
 * @return mixed $results
 */
public function afterFind($results, $primary = false) {
	$results = parent::afterFind($results, $primary);
	
	// check for the primaryKey field
	if (!isset($results[$this->primaryKey])) {
		// standard format, use the array directly
		$resultsArray = &$results;
	} else {
		// stupid format, create a dummy array
		$resultsArray = array(array());
		// and push a reference to the single value into our array
		$resultsArray[0][$this->alias] = &$results;
	}

	// iterate through $resultsArray
	foreach ($resultsArray as &$result) {
		// operate on $result[$this->alias]['fieldname']
		// one piece of code for both cases. yay!
	}

	return $results;
}

Other

Running Tests & Coverage

  • Running Tests without coverage outputs

    .\Console\cake test app All --stderr

  • Running Tests with coverage outputs

    .\Console\cake test app All --stderr --log-junit tmp/coverage/unitreport.xml --coverage-html tmp/coverage --coverage-clover tmp/coverage/coverage.xml

To see results, you can run from app\site\tmp\coverage\index.html

For CakePHP 3 it would probably be

.\phpunit --log-junit tmp/coverage/unitreport.xml --coverage-html tmp/coverage --coverage-clover tmp/coverage/coverage.xml