Tag Archives: example

CakePHP3 Cache Example – Using Curl to get a Web page contents

Heres a simple example of using the cache feature of cakephp. We want to grab a webpage contents from the web but we only want to do this once otherwise its going to be slow and waste resources.

The basic idea is that we check if the url is saved in cache, if it is then we read it in otherwise we must use curl to grab it.

CakePHP3’s Cache settings are in the config/app.php file;

* Configure the cache adapters.
'Cache' => [
'default' => [
'className' => 'File',
'path' => CACHE,
'url' => env('CACHE_DEFAULT_URL', null),
'duration' => '+60 minutes',//the duration object should cached for
/*'prefix' => 'mycacheprefix_',*/



CakePHP 3 Cache:

Cakephp3-Creating custom queries

23666In your object table;

public function findArtistBy(Query $query, array $options)
$artist = $options['search'];

return $query->where(['artist LIKE ' => $artist])
->orwhere(['title LIKE ' => $artist])
->order(['title' => 'DESC']);

In your controller method;


$this->Flash->success(__('Search complete'));

$this->set('results', $query);

So what does it do?
It will return the results where the artist field is like eg.”U2″ and where the title is like “U2”.
It also has an order clause in there and will contain the related records set “mp3files”.


Sample AJAX Call and Response

23666This is just a quick example of how to send a reply from your controller to n AJAX request.

//you controller

public function testajax(){
  $this->set('text', 'its a SUCCESS');
  $this->set('_serialize', ['text']);

//javascript function

	function test(){
			success: function(response){
			error: function (response) {

A link to call the function;

<li><?= $this->Html->link(__('updateResult'), 'javascript:test()') ?></li>


Send Form data with ajax to cakephp controller

23666The following example shows how to submit a form with AJAX to a Cakephp controller;

Jquery Javascript Funtion;

	sends the form to the controller, ensure form fields names match up 
	with escpected values.
	function testajaxaddv3(){		
			async: true,
			cache: false,
			url: 'http://localhost/mycakeapp/messages/ajaxadd',
			success: function(response) {					
			error: function(response) {					

CakePHP 3 Form:

<?= $this->Form->create(null) ?>
<legend><?= __('Add Quizzes Answer') ?></legend>
echo $this->Form->input('message');

<?= $this->Form->end() ?>

echo $this->Form->button('save',['onclick'=>'testajaxaddv3()']);


Cakephp3 How to pass a variable to an element

cake-logoSometimes its very handy to pass a variable to an Element in Cakephp3.

This allows you to customize the element if needed;
To do so simply;

in your view file;

echo $this->element('helpbox', [
    "helptext" => "Oh, this text is very helpful."

What does it do?
This will load the element called “helpbox” and pass the value “Oh, this text is very helpful.” to the variable called “helptext” in the element.

CakePHP3 Book: