[CakePHP3.10] 動的ファインダーとクエリビルダー

動的ファインダーは findBy${name} or findBy${name}Or${name} というような使い方をする

$data = $this->People->findByNameOrMail($find, $find);

クエリビルダーは検索条件を分けて書くことができる
演算子も使える

$data = $this->People->find()->where(["name"=>$find]);
$data = $this->People->find()->where(["name like"=>$find]);

// andWhere と orWhere
$arr = explode(",", $find);
$data = $this->People->find()->where(["age >=" => $arr[0]])
				->andWhere(['age >=' => $arr[1]])->order(["People.age"=>"asc"]);

			$data = $this->People->find()
				->order(["People.age" => "asc"])
				->order(["People.name" => "asc"])
				->limit(3)->page($find);

findの後をmodelのtableで定義しておいて、controllerの呼び出しメソッドで使えるのね。なるほど。

[CakePHP3.10] 検索

<p>This is People table records.</p>
<?=$this->Form->create(null, ["type"=>"post", "url"=>["controller"=>"People", "action"=>"index"]]) ?>
<div>find</div>
<div><?=$this->Form->text("People.find") ?></div>
<div><?=$this->Form->submit("検索") ?></div>
<?=$this->Form->end() ?>

Controller

	public function index(){
		if($this->request->is('post')){
			$find = $this->request->data['People']['find'];
			$condition = ['conditions'=>["name"=>$find]];
			$data = $this->People->find("all", $condition);
		} else {
			$data = $this->People->find("all");
		}
		$this->set('data', $data);
	}

### 曖昧検索

	public function index(){
		if($this->request->is('post')){
			$find = $this->request->data['People']['find'];
			$condition = ['conditions'=>["name like"=>$find]];
			$data = $this->People->find("all", $condition);
		} else {
			$data = $this->People->find("all");
		}
		$this->set('data', $data);
	}

決まった年齢以下の人だけ検索
$condition = [“conditions” => [“age <=" => $find]];

	public function index(){
		if($this->request->is('post')){
			$find = $this->request->data['People']['find'];
			$arr = explode(",", $find);
			$condition = ['conditions'=>[
				"and"=> [
					"age >=" => $arr[0],
					"age <=" => $arr[1]
				]
			]];
			$data = $this->People->find("all", $condition);
		} else {
			$data = $this->People->find("all");
		}
		$this->set('data', $data);
	}

### 並び順

	public function index(){
		if($this->request->is('post')){
			$find = $this->request->data['People']['find'];
			$condition = [
				'conditions'=>["name like" => $find],
				"order" => ["People.age" => "desc"]
			];
			$data = $this->People->find("all", $condition);
		} else {
			$data = $this->People->find("all");
		}
		$this->set('data', $data);
	}

### 必要な部分だけ取り出す
– 取り出す位置の設定「offset」
– 取り出すレコード数の設定「limit」
– 取り出すページの設定「page」

	public function index(){
		if($this->request->is('post')){
			$find = $this->request->data['People']['find'];
			$condition = [
				'limit'=> 3,
				"page" => $find
			];
			$data = $this->People->find("all", $condition);
		} else {
			$data = $this->People->find("all", ["order"=> ["People.age" => "asc"]]);
		}
		$this->set('data', $data);
	}

[CakePHP3.10] CRUD

### 特定のidを取得
get

	public function index(){
		$id = $this->request->query['id'];
		$data = $this->People->get($id);
		$this->set('data', $data);
	}

controller

	public function index(){
		$data = $this->People->find("all");
		$this->set('data', $data);
	}

	public function add(){
		$entity = $this->People->newEntity();
		$this->set('entity', $entity);
	}

	public function create(){
		if($this->request->is('post')){
			$data = $this->request->data['People'];
			$entity = $this->People->newEntity($data);
			$this->People->save($entity);
		}
		return $this->redirect(['action'=>'index']);
	}

### Edit

<p>This is People table records.</p>
<table>
<thead><tr>
	<th>id</th><th>name</th><th>mail</th><th>age</th>
</tr></thead>
<?php foreach($data->toArray() as $obj): ?>
<tr>
	<td><?=h($obj->id) ?></td>
	<td><a href="<?=$this->Url->build(["controller"=>"People", "action"=>"edit"]); ?>?id=<?=$obj->id ?>"><?=h($obj->name) ?></td>
	<td><?=h($obj->mail) ?></a></td>
	<td><?=h($obj->age) ?></td>
</tr>
<?php endforeach; ?>
</table>

ほう、なるほど〜

[CakePHP3.10] データベースを操作する

$ create database mydata;
$ use mydata;
$ create table people (
id int primary key AUTO_INCREMENT,
name varchar(100),
mail varchar(200),
age int
);

mysql> describe people;
+——-+————–+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+——-+————–+——+—–+———+—————-+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(100) | YES | | NULL | |
| mail | varchar(200) | YES | | NULL | |
| age | int | YES | | NULL | |
+——-+————–+——+—–+———+—————-+
4 rows in set (0.00 sec)

$ insert into people (name, mail, age) values
(“taro”, “taro@gmail.com”, 45),
(“hanako”, “hanako@gmail.com”, 34),
(“sachiko”, “sachiko@gmail.com”, 23),
(“ichiro”, “ichiro@gmail.com”, 12),
(“machiko”, “machiko@gmail.com”, 29);

app.php, app_local.phpを修正

    'Datasources' => [
        'default' => [
            'host' => 'localhost',
            /*
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',
            'username' => 'hoge',
            'password' => 'fuga',
            'database' => 'mydata',
            'log' => true,
            'url' => env('DATABASE_URL', null),
        ],
    ],

### エンティティとテーブル
src/Model/Entity
src/Model/Table

テーブルクラス
src/Model/Table/PeopleTable.php

namespace App\Model\Table;

use Cake\ORM\Table;

class PeopleTable extends Table {
	
}

src/Model/Entity/Person.php

namespace App\Model\Entity;

use Cake\ORM\Entity;

class Person extends Entity {
	
}

PeopleController.php

namespace AppController;

use App\Controller\AppController;

class PeopleController extends AppController {

	public function index(){
		$data = $this->People->find('all');
		$this->set('data', $data);
	}
}

src/Template/People/index.ctp

<p>This is People table records.</p>
<table>
<thead><tr>
	<th>id</th><th>name</th><th>mail</th><th>age</th>
</tr></thead>
<?php foreach($data->toArray() as $obj): ?>
<tr>
	<td><?=h($obj->id) ?></td>
	<td><?=h($obj->name) ?></td>
	<td><?=h($obj->mail) ?></td>
	<td><?=h($obj->age) ?></td>
</tr>
<?php endforeach; ?>
</table>

http://192.168.56.10:8080/people

PeopleTable.php

namespace App\Model\Table;

use Cake\ORM\Table;

class PeopleTable extends Table {
	
	public function initialize(array $config){
		parent::initialize($config);

		$this->setTable('people');
		$this->setDisplayField('name');
		$this->setPrimaryKey('id');
	}
}

Entity

class Person extends Entity {
	
	protected $_accessible = [
		'name' => true,
		'mail' => true,
		'age' => true
	];
}

なるほど、TableとEntityの使い方は何となく理解した。

[CakePHP3.10] レイアウトを作る

index.ctp

	<div class="row">
		<p>This is sample contents.</p>
		<p>これは、Helloレイアウトを利用したサンプルです。</p>	
	</div>

HelloController.php

	public function index(){

	}

### レイアウトに必要なもの
– レイアウトのテンプレート
– スタイルシートファイル
– スクリプトファイル

/webroot/css/hello.css

html {
	margin: 0px;
}
body {
	margin: 0px;
}
h1 {
	font-size: 48px;
	margin: 0px 20px;
	color: #bbf;
}
p {
	font-size: 14pt;
	color: #669;
}
.head {
	width: 100%;
	padding: 0px;
	margin: 0px;
	background-color: #f0f0ff;
}
.foot {
	position: fixed;
	bottom: 0px;
	left: 0px;
	width: 100%;
	height: 50px;
	text-align: right;
	color: #99f;
	background-color: #f0f0ff;
}
.content {
	margin: 5px 20px;
}

src/Template/Layout/hello.ctp

<!DOCTYPE html>
<html lang="en">
<head>
	<?=$this->Html->charset() ?>
	<title><?=$this->fetch("title") ?></title>
	<?=$this->Html->css("hello") ?>
	<?=$this->Html->script("hello") ?>
</head>
<body>
	<header class="head row">
		<h1><?=$this->fetch("title") ?></h1>
	</header>
	<div class="row">
		<?=$this->fetch("content") ?>
	</div>
	<footer class="foot row">
		<h5>copyright 2022 hpscript</h5>
	</footer>
</body>
</html>

HelloController.php

	public function initialize(){
		$this->viewBuilder()->setLayout("hello");
	}

Template/Element/header.ctp

<h1 style="text-align:right; font-size:30px; margin: 0px 20px;">
	title: <?=$this->fetch('title') ?>.
</h1>
<h2 style="text-align:right; font-size:16pt; margin:0px 20px; color:#ccf;">
	~ <?=$subtitle ?> ~
</h2>

Template/Element/footer.ctp

なるほどー、共通レイアウトはLayoutフォルダで、パーツはElementフォルダで、メソッドの画面は ${ControllerName}画面で構築していくのね
レイアウト周りの全体構造は理解した

[CakePHP3.10] フォームヘルパーの使い方

### チェックボックス/ラジオボタン

			<?=$this->Form->create(null, ["type"=>"post", "url"=>["controller"=>"Hello", "action"=>"index"]])?>
				<input type="hidden" name="_csrfToken" value="<?= $this->request->getParam('_csrfToken') ?>">
				<tr><th>CheckBox</th><td><?=$this->Form->checkbox("Form1.check", ["id"=>"check1"]) ?>
					<?=$this->Form->label("check1", "check box") ?>
				</td></tr>
				<tr><th>RadioButton</th><td><?=$this->Form->radio("Form1.radio", [
						["text"=>"mail", "value"=>"男性", "checked"=>true],
						["text"=>"femail","value"=>"女性"]
					]) ?></td></tr>
				<tr><th></th><td><?=$this->Form->submit("送信") ?></td></tr>
			<?=$this->Form->end() ?>

### 選択リスト

			<?=$this->Form->create(null, ["type"=>"post", "url"=>["controller"=>"Hello", "action"=>"index"]])?>
				<input type="hidden" name="_csrfToken" value="<?= $this->request->getParam('_csrfToken') ?>">
				<tr><th>Select</th><td><?=$this->Form->select("Form1.select",
				 	["one"=>"最初","two"=>"真ん中","three"=>"最後"]) ?>
				</td></tr>
				<tr><th></th><td><?=$this->Form->submit("送信") ?></td></tr>
			<?=$this->Form->end() ?>

### 複数項目の選択

			<?=$this->Form->create(null, ["type"=>"post", "url"=>["controller"=>"Hello", "action"=>"index"]])?>
				<input type="hidden" name="_csrfToken" value="<?= $this->request->getParam('_csrfToken') ?>">
				<tr><th>Select</th><td><?=$this->Form->select("Form1.select",
				 	["one"=>"最初","two"=>"2番目","three"=>"真ん中","four"=>"4番目","five"=>"最後"],
				 	["multiple"=>true, "size"=>5]) ?>
				</td></tr>
				<tr><th></th><td><?=$this->Form->submit("送信") ?></td></tr>
			<?=$this->Form->end() ?>

[CakePHP3.10] フォームの利用

<body>
	<header class="row">
		<h1><?=$title ?></h1>
	</header>
	<div class="row">
		<table>
			<form method="post" action="/mycakeapp/hello/form">
                                <input type="hidden" name="_csrfToken" value="<?= $this->request->getParam('_csrfToken') ?>">
				<tr><th>name</th><td><input type="text" name="name"></td></tr>
				<tr><th>mail</th><td><input type="text" name="mail"></td></tr>
				<tr><th>age</th><td><input type="number" name="age"></td></tr>
				<tr><th></th><button>Click</button></tr>
			</form>
		</table>
	</div>
</body>
<body>
	<header class="row">
		<h1><?=$title ?></h1>
	</header>
	<div class="row">
		<p><?=$message ?></p>
	</div>
</body>

HelloController

class HelloController extends AppController {

	public function index(){
		$this->viewBuilder()->autoLayout(false);
		$this->set('title', 'Hello!');
	}

	public function form(){
		$this->viewBuilder()->autoLayout(false);
		$name = $this->request->data['name'];
		$mail = $this->request->data['mail'];
		$age = $this->request->data['age'];
		$res = "こんにちは、" . $name . "(" . $age . 
			")さん。メールアドレスは、" . $mail . " ですね?";
		$values = [
			"title" => "Result",
			"message" => $res
		];
		$this->set($values);
	}
}

$this->request->data[“name”] でデータを取り出している

### エスケープ処理

<body>
	<header class="row">
		<h1><?=h($title) ?></h1>
	</header>
	<div class="row">
		<p><?=h($message) ?></p>
	</div>
</body>

### フォームヘルパー

		<table>
			<?=$this->Form->create(null, ["type"=>"post", "url"=>["controller"=>"Hello", "action"=>"index"]])?>
				<input type="hidden" name="_csrfToken" value="<?= $this->request->getParam('_csrfToken') ?>">
				<tr><th>name</th><td><?=$this->Form->text("Form1.name") ?></td></tr>
				<tr><th>mail</th><td><?=$this->Form->text("Form1.mail") ?></td></tr>
				<tr><th>age</th><td><?=$this->Form->text("Form1.age") ?></td></tr>
				<tr><th></th><td><?=$this->Form->submit("送信") ?></td></tr>
			<?=$this->Form->end() ?>
		</table>

Controller

	public function index(){
		$this->viewBuilder()->autoLayout(false);
		$this->set('title', 'Hello!');

		if($this->request->isPost()) {
			$this->set('data', $this->request->data['Form1']);
		} else {
			$this->set('data', []);
		

フォームヘルパーはcontrollerで呼び出さずに利用できる
なるほど

[CakePHP3.10] ビューテンプレート

public $autoRender = false; を外すとviewテンプレートが使える様になる

view templateとlayoutがある
layoutにビューテンプレートをはめ込む

src/Template/Hello/index.ctp

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Hello</title>
	<style>
		h1 {
			font-size: 60pt;
			margin: 0px 0px 10px 0px; padding: 0px 20px; color: white;
			background: linear-gradient(to right, #aaa, #fff);
		}
		p { font-size: 14pt; color: #666; }
	</style>
</head>
<body>
	<header class="row">
		<h1><?=$title ?></h1>
	</header>
	<div class="row">
		<p><?=$message ?></p>
	</div>
</body>
</html>

HelloController.php

class HelloController extends AppController {

	public function index(){
		$this->viewBuilder()->autoLayout(false);
		$this->set('title', 'Hello!');
		$this->set('message', 'This is message!');
	}
}

配列で渡す場合

	public function index(){
		$this->viewBuilder()->autoLayout(false);
		$values = [
			'title' => "hello!",
			"message" => "this is message!!!"
		];
		$this->set($values);
	}

autoLayout(false);で自動レイアウトをoffにしている

OK, controllerとviewの関係性はなんとなく分かったぞ!

CakePHP3系

内蔵サーバー
$ php ./bin/cake.php server -H 0.0.0.0 –port 8080

### View
webroot/hello.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Hello</title>
	<style>
		h1 {
			font-size: 60pt;
			margin: 0px 0px 10px 0px; padding: 0px 20px; color: white;
			background: linear-gradient(to right, #aaa, #fff);
		}
		p { font-size: 14pt; color: #666; }
	</style>
</head>
<body>
	<header class="row">
		<h1>Welcome!</h1>
	</header>
	<div class="row">
		<p>This is sample HTML page.</p>
	</div>
</body>
</html>

### Controller
src/Controller/HelloController.php

namespace App\Controller;

use App\Controller\AppController;

class HelloController extends AppController {
	public $autoRender = false;

	public function index(){
		echo "<html><body><h1>Hello!</h1>";
		echo "<p>This is sample page.</p></body></html>";
	}
}

http://192.168.56.10:8080/hello
### クエリパラメータ

	public function index(){
		$id = $this->request->query['id'];
		$pass = $this->request->query['pass'];
		echo "<html><body><h1>Hello!</h1>";
		echo "<ul><li>your id: " . $id . "</li>";
		echo "<li>password: " . $pass . "</li></ul>";
		echo "</body></html>";
	}

http://192.168.56.10:8080/hello?id=taro&pass=yamada

パラメータなしに対応
-> if文で制御する

	public function index(){
		$id = "no name";
		if(isset($this->request->query['id'])){
			$id = $this->request->query['id'];
		}
		$pass = "no password";
		if(isset($this->request->query['pass'])){
			$id = $this->request->query['pass'];
		}

		echo "<html><body><h1>Hello!</h1>";
		echo "<ul><li>your id: " . $id . "</li>";
		echo "<li>password: " . $pass . "</li></ul>";
		echo "</body></html>";
	}

オブジェクトをjsonで返す

namespace App\Controller;

use App\Controller\AppController;

class HelloController extends AppController {
	public $autoRender = false;

	private $data = [
		["name"=>"taro", "mail"=>"taro@yamada", "tel"=>"090-999-999"],
		["name"=>"hanako", "mail"=>"hanako@flower", "tel"=>"080-888-888"],
		["name"=>"sachiko", "mail"=>"sachiko@happy", "tel"=>"070-777-777"]
	];

	public function index(){
		$id = 0;
		if(isset($this->request->query['id'])){
			$id = $this->request->query['id'];
		}
		echo json_encode($this->data[$id]);
	}
}

なるほどー ちょっと理解した

[git] hotfix

git hotfixとは?
– リリースされたバージョンで発生したバグを速やかに修正するブランチ
– 修正後すぐmaster, developブランチにマージ

なるほど、そういうことか、特別な機能があるわけではなく、そういう名称で運用するって取り決めのことね。理解した。