Category Archives: cakephp3

Cakephp 3 – using uuid as primary key

In addition to use an auto-increment key as the primary key, you may also use UUID columns. CakePHP will create a unique 36 character UUID (Cake\Utility\Text::uuid()) whenever you save a new record using the Table::save() method.

From the book;
https://book.cakephp.org/3.0/en/intro/conventions.html#model-and-database-conventions

So if you create your primary key field as char(36) , cakePHP3 will generate unique uuids rather than the stand auto-incremented 1,2,3 4 keys

Credit to stackoverflow again;
http://stackoverflow.com/questions/34519770/cakephp-3-save-function-not-generating-primary-key-for-database

 

Install a new Cakephp3 Project with composer

  1. You need the php tool composer which you can get from composer.org
  2. Simply run the following command in the windows command prompt  while in your “c:\xampp\htdocs\” folder;
    composer create-project --prefer-dist cakephp/app mywebapp

    3.In your htdocs folder you should see a new folder called “my_app_name”

    Example:
    If you wanted to create an application called  “mywebapp” simply enter;

    composer create-project --prefer-dist cakephp/app mywebapp

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:
https://book.cakephp.org/3.0/en/core-libraries/caching.html

Cakephp 3- How to read a remote Xml file

23666One of the great things about CakePHP is that it has a lot of built in librarys.  Heres an example of how to read a remote XML file.

 

 

 

use Cake\Utility\Xml;
use Cake\Network\Http\Client;

//XML file you want to read in
$url="http://store.steampowered.com/feeds/newreleases.xml";

//read a remote xml file
$http = new Client();
$response = $http->get($url);
$xml = Xml::build($response->body());


//Method 1 using SimpleXMLElement Object
//loop the item elements array of xml file
foreach($xml->channel->item as $item){
	//need to cast to string
	debug ((string)$item->title);
	debug ((string)$item->link);
}


//Method 2 convert xml to array
$xml = Xml::toArray($xml);

//loop elements of array
foreach($xml['rss']['channel']['item'] as $item){
	debug ('Title:'.$item['title']);
	debug ('Link:'.$item['link']);
}

The result will print out the list of items from the feed;
http://store.steampowered.com/feeds/newreleases.xml

cakexml

 

 

 

 

 

 

More info here;
http://book.cakephp.org/3.0/en/core-libraries/xml.html#importing-data-to-xml-class

CakePhp3 – Date Formating and Timezone

23666Quite simply this is a pain to set right, as it seems to default to the american time zone despite several efforts to configure it to european time in both Cakephp3 and the Php.ini file.

But you can display the needed time format as follows in your view action;

Below the field “created” is a date field in a MySQL Database.

echo $order->created->i18nFormat('dd-MMMM-YYYY HH:mm');

Edit;

To set the timezone of your application you need to go to the config/app.php

Change below as follows;

'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
to
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_IE'),

This wont change the default display of dates but will set the dates to be displayed in the locale you desire.

edit;

MORE here

Cakephp3: Installing Cakephp3

23666Cakephp 3 depends a lot on using composer, so youll need to get that first.; http://getcomposer.org/

Once youve set up composer you can create a brand new cakephp3 app by;

  1. Going to your web servers “htdocs” folder. I.e if your using xammp it should be; C:xampphtdocs
  2. Open a command windows here and type;
    composer create-project --prefer-dist cakephp/app my_app_name
  3. Cakephp will create a folder in your htdocs folder called ” my_app_name”
  4. Open http://localhost/my_app_name

Cakephp 3 installation:
http://book.cakephp.org/3.0/en/installation.html

cakephp3 – fixing the index method for admin and normal user

23666Say for example you dont want normal users being able to see a list of items in this example lets say its questions.  But at the same time you want an “admin” user to be able to see them.

The following function might help;

 public function index(){
        
		$user_id=$this->Auth->user('id');
		$role=$this->Auth->user('role');
		
		//check users role and show all questions if admin or just their questions of normal user
		
		if($role=='admin'){
			//show all questions
			$this->paginate = [
				'limit' =>20,
				'order' => ['Questions.modified' => 'desc'],
				'contain' => ['Users', 'Questionscategories']
			];
		}
		elseif($role=='user'){
			//show only the users stuff
			//set the pagnate options
			$this->paginate = [
				'limit' =>10,
				'order' => ['Questions.modified' => 'desc'],
				'contain' => ['Users', 'Questionscategories'],
				'conditions'=>['questions.user_id'=>$user_id]
			];
		}
		

		
		
		$questions = $this->paginate($this->Questions);


        $this->set(compact('questions'));
        $this->set('_serialize', ['questions']);
    }

What it does:
basically if does a different pagnate depending in the user’s role.

Cakephp3-form methods GET and POST

23666GET:
to set the method your form is send in cakephp3 as GET;

echo $this->Form->create(null, ['type' => 'get']);

to get the Data sent via get in controller;

$this->request->query['txtboxfromform'];

POST:

//set the method
echo $this->Form->create(null, ['type' => 'post']);

 

//get data
$this->request->data['txtboxfromform'];

Forms in cakephp3:
http://book.cakephp.org/3.0/en/views/helpers/form.html

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])
->contain(['Mp3files'])
->order(['title' => 'DESC']);
}

In your controller method;

$options['search']=$search;
$query=$this->Mp3filesTags->find('ArtistBy',$options);

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

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

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”.

Reference:
http://book.cakephp.org/3.0/en/orm/query-builder.html