タグ: cakephp3

Cakephp3で検索プラグイン(friendsofcake/search)を使ってみた。

GitHubで’cakephp search’で検索 Starの多い順に並べてCakePHP3でつかそうなものからピックアップしました。で以下を採用。

friendsofcake/search
https://github.com/FriendsOfCake/search

ドキュメントのルートに行ってcomposerでインストール

$ composer require friendsofcake/search

cakeコマンドでプラグイン追加

$ ./bin/cake plugin load Search

いちおう、config/bootstrap.phpの最後あたりを確認して準備OK

Plugin::load('Search');

モデル(Table)

initializeに addBehavior()と、検索条件を追加

    public function initialize(array $config)
    {
        parent::initialize($config);
        $this->addBehavior('Search.Search');
        $this->searchManager()
            ->like('name',[
                'before' => true,
                'after' => true
            ]);

コントローラー

initializeで読み込みと使うアクション指定(ココではindex)

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Search.Prg', [
            'actions' => ['index']
        ]);
    }

モデルのfind()で ’search’ としてリクエストを渡してあげる。
containとかは普通につなげてOK

    public function index()
    {
        
        $query = $this->Products
            ->find('search',['search'=>$this->request->query])
            ->contain(['Suppliers', 'ProductStatuses', 'Components']);
        $this->set('products', $this->paginate($query));
    }

ビュー(検索フォーム)

<?php
echo $this->Form->create(null, ['valueSources' => 'query']);
echo $this->Form->input('name');
echo $this->Form->button('検索', ['type' => 'submit']);
echo $this->Form->end();
?>

検索の様子

検索の様子

詳しくは

friendsofcake/search
https://github.com/FriendsOfCake/search

Macでcakephp3 の環境構築 bakeコマンドでエラー(php.iniと、MAMPのMySQLのソケットの場所が原因でした。)

Macでcakephp3 の環境構築 bakeコマンドでエラー(php.iniと、MAMPのMySQLのソケットの場所が原因でした。)

以前Cakephp3の環境をMacにつくってうまくいっていたのですが、bakeコマンドを使ったところでエラーが発生しました。
(結果を先にいうと、CLIのPHPのphp.iniのpdo_mysql.default_socketの値とMAMPのMySQLのsocketの位置が違ってました。)

以前の環境設定の記事
MacでCakePHP3をComposerを使ってセットアップ

エラーは次のようなエラー

 % bin/cake bake all users
Bake All
---------------------------------------------------------------
One moment while associations are detected.
Exception: SQLSTATE[HY000] [2002] No such file or directory in [/Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Driver/PDODriverTrait.php, line 47]
2017-08-29 02:34:48 Error: [PDOException] SQLSTATE[HY000] [2002] No such file or directory in /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Driver/PDODriverTrait.php on line 47
Stack Trace:
#0 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Driver/PDODriverTrait.php(47): PDO->__construct('mysql:host=loca...', 'root', 'root', Array)
#1 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Driver/Mysql.php(104): CakeDatabaseDriverMysql->_connect('mysql:host=loca...', Array)
#2 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Schema/BaseSchema.php(45): CakeDatabaseDriverMysql->connect()
#3 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Dialect/MysqlDialectTrait.php(63): CakeDatabaseSchemaBaseSchema->__construct(Object(CakeDatabaseDriverMysql))
#4 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Schema/Collection.php(52): CakeDatabaseDriverMysql->schemaDialect()
#5 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Schema/CachedCollection.php(42): CakeDatabaseSchemaCollection->__construct(Object(CakeDatabaseConnection))
#6 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Connection.php(368): CakeDatabaseSchemaCachedCollection->__construct(Object(CakeDatabaseConnection), true)
#7 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Connection.php(387): CakeDatabaseConnection->getSchemaCollection()
#8 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(1016): CakeDatabaseConnection->schemaCollection()
#9 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(968): BakeShellTaskModelTask->_getAllTables()
#10 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(209): BakeShellTaskModelTask->listAll()
#11 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(127): BakeShellTaskModelTask->getAssociations(Object(CakeORMTable))
#12 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(110): BakeShellTaskModelTask->getTableContext(Object(CakeORMTable), 'users', 'Users')
#13 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/bake/src/Shell/Task/ModelTask.php(97): BakeShellTaskModelTask->bake('Users')
#14 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/bake/src/Shell/BakeShell.php(257): BakeShellTaskModelTask->main('Users')
#15 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Collection/CollectionTrait.php(51): BakeShellBakeShell->BakeShell{closure}('Users', 0)
#16 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/bake/src/Shell/BakeShell.php(258): CakeCollectionCollection->each(Object(Closure))
#17 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Console/Shell.php(494): BakeShellBakeShell->all('users')
#18 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Console/CommandRunner.php(140): CakeConsoleShell->runCommand(Array, true)
#19 /Users/taka/htdocs/_template/php/cakephp3/bookmarker/bin/cake.php(12): CakeConsoleCommandRunner->run(Array)
#20 {main}

エラーを読んでいきます。

Exception: SQLSTATE[HY000] [2002] No such file or directory in [/Users/taka/htdocs/_template/php/cakephp3/bookmarker/vendor/cakephp/cakephp/src/Database/Driver/PDODriverTrait.php, line 47]

PDOのドライバーのクラスでファイルが見つからないらしい。該当箇所を見る。

$connection = new PDO(
            $dsn,
            $config['username'],
            $config['password'],
            $config['flags']
        );

PDOをnewしているところでエラーなのでPDO自体がまずいのか。
phpinfoのPDOを探ってみる。

% php --info | less
//で、PDO部分を検索
PDO

PDO support => enabled
PDO drivers => mysql, odbc, sqlite

pdo_mysql

PDO Driver for MySQL => enabled
Client API version => mysqlnd 5.0.12-dev - 20150407 - $Id: b396954eeb2d1d9ed7902b8bae237b287f21ad9e $

Directive => Local Value => Master Value
pdo_mysql.default_socket => /tmp/mysql.sock => /tmp/mysql.sock

PDO_ODBC

PDO Driver for ODBC (unixODBC) => enabled
ODBC Connection Pooling => Enabled, strict matching

pdo_sqlite

PDO Driver for SQLite 3.x => enabled
SQLite Library => 3.15.1

あー、たしかMAMPのmysqlのソケットの場所が違ったはず。と思い出す。
シンボリックリンク作成

% ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock

気を取り直してもう一いっかいで、うまくいきました。

% bin/cake bake all users
Bake All
---------------------------------------------------------------
One moment while associations are detected.

Baking table class for Users...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Model/Table/UsersTable.php
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Model/Table/UsersTable.php`
Deleted `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Model/Table/empty`

Baking entity class for User...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Model/Entity/User.php
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Model/Entity/User.php`
Deleted `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Model/Entity/empty`

Baking test fixture for Users...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/tests/Fixture/UsersFixture.php
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/tests/Fixture/UsersFixture.php`
Deleted `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/tests/Fixture/empty`
Bake is detecting possible fixtures...

Baking test case for AppModelTableUsersTable ...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/tests/TestCase/Model/Table/UsersTableTest.php
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/tests/TestCase/Model/Table/UsersTableTest.php`

Baking controller class for Users...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Controller/UsersController.php
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Controller/UsersController.php`
Bake is detecting possible fixtures...

Baking test case for AppControllerUsersController ...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/tests/TestCase/Controller/UsersControllerTest.php
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/tests/TestCase/Controller/UsersControllerTest.php`

Baking `index` view template file...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Template/Users/index.ctp
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Template/Users/index.ctp`

Baking `view` view template file...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Template/Users/view.ctp
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Template/Users/view.ctp`

Baking `add` view template file...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Template/Users/add.ctp
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Template/Users/add.ctp`

Baking `edit` view template file...

Creating file /Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Template/Users/edit.ctp
Wrote `/Users/taka/htdocs/_template/php/cakephp3/bookmarker/src/Template/Users/edit.ctp`
Bake All complete.

MacでCakePHP3をComposerを使ってセットアップ

MacでCakePHP3をComposerを使ってセットアップ

title

title

まずMacにHomebrew版のPHPをインストール。

参考 : MacのPHPをphp7へ変更(HomeBrewでPHP71のインストール)

PHP拡張のintlをインストール

CakePHPではIntl(国際化用拡張モジュール ICUのラッパー)が使われるので先にインストール

(参考サイト)
http://php.net/manual/ja/intro.intl.php
https://book.cakephp.org/3.0/ja/installation.html

brewを検索

$ brew search intl
homebrew/php/php53-intl     homebrew/php/php54-intl     homebrew/php/php55-intl     homebrew/php/php56-intl     homebrew/php/php70-intl     homebrew/php/php71-intl     homebrew/php/php72-intl     intltool

インストール

$ brew install php71-intl 
==> Installing php71-intl from homebrew/php
==> Downloading https://homebrew.bintray.com/bottles-php/php71-intl-7.1.8_18.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring php71-intl-7.1.8_18.sierra.bottle.tar.gz
==> Caveats
To finish installing intl for PHP 7.1:
  * /usr/local/etc/php/7.1/conf.d/ext-intl.ini was created,
    do not forget to remove it upon extension removal.
  * Validate installation via one of the following methods:
  *
  * Using PHP from a webserver:
  * - Restart your webserver.
  * - Write a PHP page that calls "phpinfo();"
  * - Load it in a browser and look for the info on the intl module.
  * - If you see it, you have been successful!
  *
  * Using PHP from the command line:
  * - Run `php -i "(command-line 'phpinfo()')"`
  * - Look for the info on the intl module.
  * - If you see it, you have been successful!
==> Summary
🍺  /usr/local/Cellar/php71-intl/7.1.8_18: 7 files, 552.6KB

プロジェクトをつくってみる

公式サイトを参考にcomposerのcreate-projectでプロジェクトを作ってみる。

(参考)
インストール | Cakephp
Composerのcreate-projectが何をやっているのか調べてみた

以下実行ろぐ。
composer self-updateは実行済で、途中で パーミッション設定する?(Set Folder Permissions ? (Default to Y) [Y,n]? y)と聞かれるのでyと答えた。

$ composer create-project --prefer-dist cakephp/app my_app_name
Installing cakephp/app (3.5.0)
  - Installing cakephp/app (3.5.0): Loading from cache
Created project in my_app_name
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 39 installs, 0 updates, 0 removals
  - Installing cakephp/plugin-installer (1.0.0): Downloading (100%)         
  - Installing aura/intl (3.0.0): Downloading (100%)         
  - Installing mobiledetect/mobiledetectlib (2.8.25): Downloading (100%)         
  - Installing psr/http-message (1.0.1): Downloading (100%)         
  - Installing zendframework/zend-diactoros (1.4.1): Downloading (100%)         
  - Installing psr/log (1.0.2): Downloading (100%)         
  - Installing cakephp/chronos (1.1.2): Downloading (100%)         
  - Installing cakephp/cakephp (3.5.0): Downloading (100%)         
  - Installing symfony/polyfill-mbstring (v1.5.0): Downloading (100%)         
  - Installing symfony/yaml (v3.3.6): Downloading (100%)         
  - Installing symfony/debug (v3.3.6): Downloading (100%)         
  - Installing symfony/console (v3.3.6): Downloading (100%)         
  - Installing symfony/filesystem (v3.3.6): Downloading (100%)         
  - Installing symfony/config (v3.3.6): Downloading (100%)         
  - Installing robmorgan/phinx (v0.8.1): Downloading (100%)         
  - Installing cakephp/migrations (1.7.1): Downloading (100%)         
  - Installing m1/env (2.1.0): Downloading (100%)         
  - Installing josegonzalez/dotenv (2.1.0): Downloading (100%)         
  - Installing jakub-onderka/php-console-color (0.1): Downloading (100%)         
  - Installing jakub-onderka/php-console-highlighter (v0.3.2): Downloading (100%)         
  - Installing dnoegel/php-xdg-base-dir (0.1): Downloading (100%)         
  - Installing nikic/php-parser (v3.1.0): Downloading (100%)         
  - Installing symfony/var-dumper (v3.3.6): Downloading (100%)         
  - Installing psy/psysh (v0.8.11): Downloading (100%)         
  - Installing jdorn/sql-formatter (v1.2.17): Downloading (100%)         
  - Installing symfony/process (v3.3.6): Downloading (100%)         
  - Installing symfony/finder (v3.3.6): Downloading (100%)         
  - Installing seld/phar-utils (1.0.1): Downloading (100%)         
  - Installing seld/jsonlint (1.6.1): Downloading (100%)         
  - Installing seld/cli-prompt (1.0.3): Downloading (100%)         
  - Installing justinrainbow/json-schema (5.2.1): Downloading (100%)         
  - Installing composer/spdx-licenses (1.1.6): Downloading (100%)         
  - Installing composer/semver (1.4.2): Downloading (100%)         
  - Installing composer/ca-bundle (1.0.7): Downloading (100%)         
  - Installing composer/composer (1.5.1): Downloading (100%)         
  - Installing cakephp/debug_kit (3.11.0): Downloading (100%)         
  - Installing cakephp/bake (1.4.1): Downloading (100%)         
  - Installing squizlabs/php_codesniffer (3.0.2): Downloading (100%)         
  - Installing cakephp/cakephp-codesniffer (3.0.1): Downloading (100%)         
cakephp/app suggests installing markstory/asset_compress (An asset compression plugin which provides file concatenation and a flexible filter system for preprocessing and minification.)
cakephp/app suggests installing dereuromark/cakephp-ide-helper (After baking your code, this keeps your annotations in sync with the code evolving from there on for maximum IDE and PHPStan compatibility.)
cakephp/app suggests installing phpunit/phpunit (Allows automated tests to be run without system-wide install.)
cakephp/cakephp suggests installing lib-ICU (The intl PHP library, to use Text::transliterate() or Text::slug())
symfony/console suggests installing symfony/event-dispatcher ()
m1/env suggests installing m1/vars (For loading of configs)
symfony/var-dumper suggests installing ext-symfony_debug ()
psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)
psy/psysh suggests installing hoa/console (A pure PHP readline implementation. You'll want this if your PHP install doesn't already support readline or libedit.)
cakephp/debug_kit suggests installing ext-sqlite (DebugKit needs to store panel data in a database. SQLite is simple and easy to use.)
Writing lock file
Generating autoload files
> CakeComposerInstallerPluginInstaller::postAutoloadDump
> AppConsoleInstaller::postInstall
Created `config/app.php` file
Set Folder Permissions ? (Default to Y) [Y,n]? y
Permissions set on /Users/taka/htdocs/my_app_name/tmp/cache
Permissions set on /Users/taka/htdocs/my_app_name/tmp/cache/models
Permissions set on /Users/taka/htdocs/my_app_name/tmp/cache/persistent
Permissions set on /Users/taka/htdocs/my_app_name/tmp/cache/views
Permissions set on /Users/taka/htdocs/my_app_name/tmp/sessions
Permissions set on /Users/taka/htdocs/my_app_name/tmp/tests
Permissions set on /Users/taka/htdocs/my_app_name/tmp
Permissions set on /Users/taka/htdocs/my_app_name/logs
Updated Security.salt value in config/app.php

ローカルサーバーを起動して確認

ローカルのApacheを起動して webrootをドキュメントルートに指定してアクセス。
うまく行った模様あとはDBとかsaltとか設定すれば大丈夫そう。パーミッションとか自動でやってくれるのは助かる。DBの設定とか、saltの設定などまとめて行うシェルスクリプトとか書いておくともっと楽にプロジェクト作れそうだけど、そこまで頻度ないか。

title

title

Powered by WordPress & Theme by Anders Norén