Skip to content

Instantly share code, notes, and snippets.

@katsuobushiFPGA
Last active February 22, 2017 12:34
Show Gist options
  • Save katsuobushiFPGA/445bec5003ac0996d1f07388d81fccd7 to your computer and use it in GitHub Desktop.
Save katsuobushiFPGA/445bec5003ac0996d1f07388d81fccd7 to your computer and use it in GitHub Desktop.
<?php
//entity class
// src/Model/Entity/Article.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Article extends Entity
{
}
//entity create
use App\Model\Entity\Article;
$article = new Article();
//another
use Cake\ORM\TableRegistry;
$article = TableRegistry::get('Articles')->newEntity();
$article = TableRegistry::get('Articles')->newEntity([
'id' => 1,
'title' => 'New Article',
'created' => new DateTime('now')
]);
//entity access
use App\Model\Entity\Article;
$article = new Article;
$article->title = 'This is my first post';
echo $article->title;
$article->set('title', 'This is my first post');
echo $article->get('title');
$article->set([
'title' => 'My first post',
'body' => 'It is the best ever!'
]);
//entity save
//Tableくらすのsaveに渡す
use Cake\ORM\TableRegistry;
$articlesTable = TableRegistry::get('Articles');
$article = $articlesTable->newEntity();
$article->title = '新しい記事';
$article->body = 'これは記事の本文です';
if ($articlesTable->save($article)) {
// $article エンティティは今や id を持っています
$id = $article->id;
}
//update
use Cake\ORM\TableRegistry;
$articlesTable = TableRegistry::get('Articles');
$article = $articlesTable->get(12); // id 12 の記事を返します
$article->title = 'CakePHP は最高のフレームワークです!';
$articlesTable->save($article);
//getter setter
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Article extends Entity {
// フィールド名の先頭に'get'をつける
public function getTitle($title) {
return ucwords($title);
}
// フィールド名の先頭に'set'をつける
public function setTitle($title) {
// set(key, value)で$_properties配列にデータをセット
$this->set('slug', Inflector::slug($title));
return $title;
}
// 複数フィールドの値を加工して取得したい場合、メソッド名のget,setの後ろは自由
public function getFullName() {
// クエリで取得した値、もしくはset()でセットした値を$_propertiesから取得
return $this->_properties['first_name'] . ' ' .
$this->_properties['last_name'];
}
}
//バリデーションメソッド
//作るなら、Tableクラスに生成する
//バリデーションエラー
// すべて取得
$errors = $user->errors();
// フィールドを指定して取得
$errors = $user->errors('password');
// メッセージをセット
$user->errors('password', ['Password is required.']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment