Laminasを使ってみる
データベースとモデル
データベース
Now that we have the Album module set up with controller action methods and view scripts, it is time to look at the model section of our application. Remember that the model is the part that deals with the application’s core purpose (the so-called “business rules”) and, in our case, deals with the database. We will make use of laminas-db’s Laminas\Db\TableGateway\TableGateway to find, insert, update, and delete rows from a database table.
We are going to use Sqlite, via PHP’s PDO driver. Create a text file data/schema.sql with the following contents:
CREATE TABLE album (id INTEGER PRIMARY KEY AUTOINCREMENT, artist varchar(100) NOT NULL, title varchar(100) NOT NULL);
INSERT INTO album (artist, title) VALUES ('The Military Wives', 'In My Dreams');
INSERT INTO album (artist, title) VALUES ('Adele', '21');
INSERT INTO album (artist, title) VALUES ('Bruce Springsteen', 'Wrecking Ball (Deluxe)');
INSERT INTO album (artist, title) VALUES ('Lana Del Rey', 'Born To Die');
INSERT INTO album (artist, title) VALUES ('Gotye', 'Making Mirrors');
(The test data chosen happens to be the Bestsellers on Amazon UK at the time of writing!)
Now create the database using the following:
module/Album/src/ModelにAlbumTable.phpを作る。
namespace Album\Model;
class Album
{
public $id;
public $artist;
public $title;
public function exchangeArray(array $data)
{
$this->id = !empty($data['id']) ? $data['id'] : null;
$this->artist = !empty($data['artist']) ? $data['artist'] : null;
$this->title = !empty($data['title']) ? $data['title'] : null;
}
}
Laminas\Db\Adapter\AdapterInterfaceサービスはlaminas-dbコンポーネントによって登録されます。以前、config/modules.config.phpに次のエントリが含まれていることに気づいたかもしれません。:
return [
'Laminas\Form',
'Laminas\Db',
'Laminas\Router',
'Laminas\Validator',
/* ... */
],
All Laminas components that provide laminas-servicemanager configuration are also exposed as modules themselves; the prompts as to where to register the components during our initial installation occurred to ensure that the above entries are created for you.
The end result is that we can already rely on having a factory for the Laminas\Db\Adapter\AdapterInterface service; now we need to provide configuration so it can create an adapter for us.
LaminasのModuleManagerは、各モジュールのmodule.config.phpファイルからすべてのconfigurationをマージしてからconfig/autoload/ (first *.global.php files, and then *.local.php files)にマージします。データベースconfiguration情報をバージョン管理システムにコミットすべきglobal.phpに追加します。必要に応じてlocal.php (バージョン管理システム外) にデータベースの資格情報を保存できます。 次のコードを使用してconfig/autoload/global.php(アルバムモジュール内ではなくプロジェクトルート内)を変更します。 :
return [
'db' => [
'driver' => 'Pdo',
'dsn' => sprintf('sqlite:%s/data/laminastutorial.db', realpath(getcwd())),
],
];