Zend Frameworkで作業している間、作業を簡単にするカスタムヘルパーが必要になることがよくあります.zf1ではヘルパーからデータベースモデルにアクセスするのは簡単でしたが、カスタムビューヘルパーで任意のテーブルのデータベースモデルにアクセスする方法に行き詰まりました.それが必要なので、ビュー内の新しい db アダプター オブジェクトを作成することによって、専門外の方法で問題を回避します。これは決して良い方法ではありませんでしたが、最近、ビュー ヘルパーでデータベース アダプターにアクセスするための非常に興味深い方法を知るようになりました。任意のテーブルで任意のクエリを実行するには、Zend F2 の方法ではなく、問題を解決するための非常にシンプルで短い方法です。
これが私のモデルの例です...
<?php
namespace Application\Model;
use Zend\Db\TableGateway\TableGateway;
class SlideImageSubTable {
protected $tableGateway;
public $adapter;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
$this->adapter = $this->tableGateway->getAdapter();
}
public function fetchAll() {
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getSlideImageSub($id) {
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function getImageMenu($id) {
$id = (int) $id;
$rowset = $this->tableGateway->select(array('slide_image_id' => $id));
$rows = array_values(iterator_to_array($rowset));
if (!$rows) {
throw new \Exception("Could not find row $id");
}
return $rows;
}
public function saveSlideImageSub(SlideImageSub $slideImageSub) {
$data = array(
'slide_image_id' => $slideImageSub->slide_image_id,
'title' => $slideImageSub->title,
'description' => $slideImageSub->description
);
$id = (int) $slideImageSub->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getSlideImageSub($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
public function deleteSlideImageSub($id) {
$this->tableGateway->delete(array('id' => $id));
}
}
「public $adapter」パブリック変数を見てください。コンストラクターでは、$this->tableGateway->getAdapter(); を呼び出して初期化します。メソッド、getAdapter() は、ゲートウェイ オブジェクトを通じて使用できます。
次に、コントローラーアクションビューで、それを任意の変数に割り当て、その変数をビューページに渡す必要があります。このような..
public function equitiesAction() {
$image_id = $this->params('id');
$result = $this->getTable('SlideImageSub')->getImageMenu($image_id);
$adapter = $this->table->adapter;
$view = new ViewModel(array(
'result' => $result,
'adapter' => $adapter,
));
return $view;
}
ビューでは、このように「アダプター」オブジェクトをカスタムビューに渡します..
<?php echo $this->GetMenuProducts( $this->adapter); ?>
カスタム ビューでは、このデータベース アダプター オブジェクトを使用して、任意のテーブルで選択クエリを作成できます。
これが誰かの役に立てば幸いです。カスタム ビュー ヘルパーでデータベース アクセスを使用する方法を調べましたが、提供された構成方法が機能しませんでした。
ありがとう