Zend-framework-working-example

提供:Dev Guides
移動先:案内検索

Zend Framework-動作例

この章では、Zend FrameworkでMVCベースの完全な従業員アプリケーションを作成する方法を学びます。 以下の手順に従ってください。

ステップ1:Module.php

まず、myapp/module/Employee/src/ディレクトリ内にEmployeeモジュールを作成してから、ConfigProviderInterfaceインターフェイスを実装する必要があります。

Moduleクラスの完全なコードは次のとおりです-

<?php
namespace Employee;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface {
   public function getConfig() {
      return include __DIR__ . '/../config/module.config.php';
   }
}

ステップ2:composer.json

次のコードを使用して、autoloadセクションの composer.jsonTutorial モジュールを構成します。

"autoload": {
   "psr-4": {
      "Application\\": "module/Application/src/",
      "Tutorial\\": "module/Tutorial/src/",
      "Employee\\": "module/Employee/src/"
   }
}

次に、composer updateコマンドを使用してアプリケーションを更新します。

composer update

Composerコマンドは、アプリケーションに必要な変更を行い、以下のコマンドプロンプトに表示されるようにログを表示します。

Loading composer repositories with package information
Updating dependencies (including require-dev)
   - Removing zendframework/zend-component-installer (0.3.0)
   - Installing zendframework/zend-component-installer (0.3.1)
   Downloading: 100%

   - Removing zendframework/zend-stdlib (3.0.1)
   - Installing zendframework/zend-stdlib (3.1.0)
   Loading from cache

   - Removing zendframework/zend-eventmanager (3.0.1)
   - Installing zendframework/zend-eventmanager (3.1.0)
   Downloading: 100%

   - Removing zendframework/zend-view (2.8.0)
   - Installing zendframework/zend-view (2.8.1)
   Loading from cache

   - Removing zendframework/zend-servicemanager (3.1.0)
   - Installing zendframework/zend-servicemanager (3.2.0)
   Downloading: 100%

   - Removing zendframework/zend-escaper (2.5.1)
   - Installing zendframework/zend-escaper (2.5.2)
   Loading from cache

   - Removing zendframework/zend-http (2.5.4)
   - Installing zendframework/zend-http (2.5.5)
   Loading from cache

   - Removing zendframework/zend-mvc (3.0.1)
   - Installing zendframework/zend-mvc (3.0.4)
   Downloading: 100%

   - Removing phpunit/phpunit (5.7.4)
   - Installing phpunit/phpunit (5.7.5)
   Downloading: 100%

Writing lock file
Generating autoload files

ステップ3:従業員モジュールのmodule.config.php

次のコードを使用して、myapp/module/Employee/configの下にモジュール構成ファイル「module.config.php」を作成します。

<?php
namespace Employee;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Router\Http\Segment;
return [
   'controllers' => [
      'factories' => [
         Controller\EmployeeController::class => InvokableFactory::class,
      ],
   ],
   'view_manager' => [
      'template_path_stack' => ['employee' => __DIR__ . '/../view',],
   ],
];

次に、アプリケーションレベルの構成ファイルmyapp/config/modules.config.phpでEmployeeモジュールを構成します。

return ['Zend\Router', 'Zend\Validator', 'Application', 'Tutorial', 'Employee'];

ステップ4:EmployeeController

AbstractActionControllerを拡張して新しいPHPクラスEmployeeControllerを作成し、myapp/module/Employee/src/Controllerディレクトリに配置します。

完全なコードリストは次のとおりです-

<?php
namespace Employee\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class EmployeeController extends AbstractActionController {
   public function indexAction() {
      return new ViewModel();
   }
}

ステップ5:ルーターの構成

Employeeモジュールにセグメントルートを追加しましょう。 myapp/module/Employee/configにある従業員モジュール構成ファイルmodule.config.phpを更新します。

<?php
namespace Employee;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Router\Http\Segment;
return [
   'controllers' => [
      'factories' => [
         Controller\EmployeeController::class => InvokableFactory::class,
      ],
   ],
   'router' => [
      'routes' => [
         'employee' => [
            'type' => Segment::class,
            'options' => [
               'route' => '/employee[/:action[/:id]]',
               'constraints' => [
                  'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
                  'id' => '[0-9]+',
               ],
               'defaults' => [
                  'controller' => Controller\EmployeeController::class,
                  'action' => 'index',
               ],
            ],
         ],
      ],
   ],
   'view_manager' => [
      'template_path_stack' => [
         'employee' => __DIR__ . '/../view',
      ],
   ],
];

Employeeモジュールのルーティングを追加しました。 次のステップは、Employeeアプリケーションのビュースクリプトを作成することです。

ステップ6:ViewModelを作成する

myapp/module/Employee/view/employee/employeeディレクトリの下に「index.phtml」というファイルを作成します。

ファイルに次の変更を追加します-

<div class = "row content">
   <h3>This is my first Zend application</h3>
</div>
Move to “EmployeeController.php” file and edit the following changes,

<?php
namespace Employee\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class EmployeeController extends AbstractActionController {
   public function indexAction() {
      return new ViewModel();
   }
}

最後に、Employeeモジュールが正常に完了しました。 次のURLを使用してアクセスできます- http://localhost:8080/employee

結果

アプリケーションテンプレート

次のステップでは、従業員アプリケーションで*追加、編集*および*削除*データ操作を実行します。 これらの操作を実行するには、最初にデータベースモデルを作成する必要があります。 次のステップで説明します。

ステップ7:モデルを作成する

モジュール* srcディレクトリ*にモデルEmployeeを作成しましょう。 通常、モデルはModelフォルダー(myapp/module/Employee/src/Model/Employee.php)の下にグループ化されます

<?php
namespace Employee\Model;
class Employee {
   public $id;
   public $emp_name;
   public $emp_job;
}

ステップ8:MySQLテーブル

次のコマンドを使用して、ローカルMYSQLサーバーに tutorials という名前のデータベースを作成します-

create database tutorials;

次のSQLコマンドを使用して、データベースに employee という名前のテーブルを作成しましょう-

use tutorials;
CREATE TABLE employee (
   id int(11) NOT NULL auto_increment,
   emp_name varchar(100) NOT NULL,
   emp_job varchar(100) NOT NULL,
   PRIMARY KEY (id)
);

次のクエリを使用して employee テーブルにデータを挿入します-

INSERT INTO employee (emp_name, emp_job) VALUES ('Adam',  'Tutor');
INSERT INTO employee (emp_name, emp_job) VALUES ('Bruce',  'Programmer');
INSERT INTO employee (emp_name, emp_job) VALUES ('David',  'Designer');

ステップ9:データベース構成の更新

グローバル構成ファイルmyapp/config/autoload/global.phpを必要なデータベースドライブ情報で更新します。

return [
   'db' => [
      'driver' => 'Pdo',
      'dsn' => 'mysql:dbname = tutorials;host=localhost',
      'driver_options' => [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''],
   ],
];

次に、ローカル構成ファイル(myapp/config/autoload/local.php)のデータベース資格情報を更新します。 このようにして、ローカルとライブのデータベース接続資格情報を分離できます。

<?php
return array(
   'db' => array('username' => '<user_name>', 'password' => '<password>',),
);

ステップ10:exchangeArrayを実装する

EmployeeモデルにexchangeArray関数を実装します。

<?php
namespace Employee\Model;
class Employee {
   public $id;
   public $emp_name;
   public $emp_job;
   public function exchangeArray($data) {
      $this->id = (!empty($data['id'])) ? $data['id'] : null;
      $this->emp_name = (!empty($data['emp_name'])) ? $data['emp_name'] : null;
      $this->emp_job = (!empty($data['emp_job'])) ? $data['emp_job'] : null;
   }
}

ステップ11:TableGatewayを使用して従業員データを取得する

Modelフォルダー自体にEmployeeTableクラスを作成します。 次のコードブロックで定義されています。

<?php
namespace Employee\Model;
use Zend\Db\TableGateway\TableGatewayInterface;
class EmployeeTable {
   protected $tableGateway;
   public function __construct(TableGatewayInterface $tableGateway) {
      $this->tableGateway = $tableGateway;
   }
   public function fetchAll() {
      $resultSet = $this->tableGateway->select();
      return $resultSet;
   }
}

ステップ12:EmployeeTableクラスを構成する

_getServiceConfig()_メソッドを使用して_Module.php_の従業員サービスを更新する

<?php
namespace Employee;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;

class Module implements ConfigProviderInterface {
   public function getConfig() {
      return include __DIR__ . '/../config/module.config.php';
   }
   public function getServiceConfig() {
      return [
         'factories' => [
            Model\EmployeeTable::class => function (    $container) {
               $tableGateway = $container>get( Model\EmployeeTableGateway::class);
               $table = new Model\EmployeeTable($tableGateway);
               return $table;
            },
            Model\EmployeeTableGateway::class => function ($container) {
               $dbAdapter = $container->get(AdapterInterface::class);
               $resultSetPrototype = new ResultSet();
               $resultSetPrototype->setArrayObjectPrototype(new Model\Employee());
               return new TableGateway('employee', $dbAdapter, null, $resultSetPrototype);
            },
         ],
      ];
   }
}

ステップ13:コントローラーに従業員サービスを追加する

以下に示すように、myapp/module/config/module.config.phpのEmployee Module Configurationのコントローラーセクションを更新します。

'controllers' => [
   'factories' => [
      Controller\EmployeeController::class => function($container) {
         return new Controller\EmployeeController(
            $container->get(Model\EmployeeTable::class)
         );
      },
   ],
]

ステップ14:EmployeeControllerのコンストラクターを追加する

引数として EmployeeTable を使用してコンストラクターを追加し、次の変更を編集します。

<?php
namespace Employee\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Employee\Model\Employee;
use Employee\Model\EmployeeTable;

class EmployeeController extends AbstractActionController {
   private $table;
   public function __construct(EmployeeTable $table) {
      $this->table = $table;
   }
   public function indexAction() {
      $view = new ViewModel([
         'data' => $this->table->fetchAll(),
      ]);
      return $view;
   }
}

ステップ15:ビュースクリプト「index.phtml」で従業員情報を表示する

ファイルに移動します- index.phtml および次の変更を行います-

<?php
$title = 'Employee application';
$this->headTitle($title);
?>

<table class="table">
   <tr>
      <th>Employee Name</th>
      <th>Employee Job</th>
      <th>Edit/Delete operations</th>
   </tr>
   <?php foreach ($data as $empdata) : ?>
   <tr>
      <td><?php echo $this->escapeHtml($empdata->emp_name);?></td>
      <td><?php echo $this->escapeHtml($empdata->emp_job);?></td>
      <td>
         <a href="<?php echo $this->url('employee',
            array('action'=>'edit', 'id' =>$empdata->id));?>">Edit</a>
         <a href="<?php echo $this->url('employee',
            array('action'=>'delete', 'id' => $empdata->id));?>">Delete</a>
      </td>
   </tr>
   <?php endforeach; ?>
</table>

これでデータベースモデルが正常に作成され、アプリケーション内のレコードを取得できます。

url- http://localhost:8080/employee を使用してアプリケーションを要求します。

結果

成功したデータベース

次のステップでは、従業員モジュールでの*挿入、編集*および*削除*データ操作について説明します。

ステップ16:従業員フォームを作成する

myapp/module/Employee/src/Formディレクトリに EmployeeForm.php というファイルを作成します。 以下のコードブロックで説明します。

<?php
namespace Employee\Form;
use Zend\Form\Form;

class EmployeeForm extends Form {
   public function __construct($name = null) {
     /
     /we want to ignore the name passed
      parent::__construct('employee');
      $this->add(array(
         'name' => 'id',
         'type' => 'Hidden',
      ));
      $this->add(array(
         'name' => 'emp_name',
         'type' => 'Text',
         'options' => array(
            'label' => 'Name',
         ),
      ));
      $this->add(array(
         'name' => 'emp_job',
         'type' => 'Text',
         'options' => array(
            'label' => 'Job',
         ),
      ));
      $this->add(array(
         'name' => 'submit',
         'type' => 'Submit',
         'attributes' => array(
            'value' => 'Go',
            'id' => 'submitbutton',
         ),
      ));
   }
}

ステップ17:従業員モデルを更新する

従業員モデルを更新し、InputFilterAwareInterfaceを実装します。 ディレクトリmyapp/module/Employee/src/Employee/Modelに移動し、 Employee.phpfile に次の変更を追加します。

<?php
namespace Employee\Model;

//Add these import statements
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class Employee implements InputFilterAwareInterface {
   public $id;
   public $emp_name;
   public $emp_job;
   protected $inputFilter;
   public function exchangeArray($data) {
      $this->id = (isset($data['id'])) ? $data['id'] : null;
      $this->emp_name = (isset($data['emp_name'])) ? $data['emp_name'] : null;
      $this->emp_job = (isset($data['emp_job']))  ? $data['emp_job'] : null;
   }

  //Add content to these methods:
   public function setInputFilter(InputFilterInterface $inputFilter) {
      throw new \Exception("Not used");
   }
   public function getInputFilter() {
      if (!$this->inputFilter) {
         $inputFilter = new InputFilter();
         $inputFilter->add(array(
            'name' => 'id',
            'required' => true,
            'filters' => array(
               array('name' => 'Int'),
            ),
         ));
         $inputFilter->add(array(
            'name' => 'emp_name',
            'required' => true,
            'filters' => array(
               array('name' => 'StripTags'),
               array('name' => 'StringTrim'),
            ),
            'validators' => array(
               array('name' => 'StringLength',
                        'options' => array(
                           'encoding' => 'UTF-8',
                           'min' => 1,
                           'max' => 50,
                        ),
                    ),
                ),
            ));
         $inputFilter->add(array(
            'name' => 'emp_job',
            'required' => true,
            'filters' => array(
               array('name' => 'StripTags'),
               array('name' => 'StringTrim'),
            ),
            'validators' => array(
               array('name' => 'StringLength',
                  'options' => array(
                     'encoding' => 'UTF-8',
                     'min' => 1,
                     'max' => 50,
                  ),
                  ),
               ),
         ));
         $this->inputFilter = $inputFilter;
      }
      return $this->inputFilter;
   }
}

ステップ18:Employee ControllerにaddActionを追加します

*EmployeeController* クラスに次の変更を追加します。
<?php
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Employee\Model\Employee;
use Employee\Model\EmployeeTable;
use Employee\Form\EmployeeForm;

public function addAction() {
   $form = new EmployeeForm();
   $form->get('submit')->setValue('Add');
   $request = $this->getRequest();

   if ($request->isPost()) {
      $employee = new Employee();
      $form->setInputFilter($employee->getInputFilter());
      $form->setData($request->getPost());

      if ($form->isValid()) {
         $employee->exchangeArray($form->getData());
         $this->table->saveEmployee($employee);

        //Redirect to list of employees
         return $this->redirect()->toRoute('employee');
      }
   }
   return array('form' => $form);
}

ステップ19:EmployeeTableクラスに保存機能を追加する

次の2つの関数をEmployeeTableクラスに追加します– myapp/module/Employee/src/Model/EmployeeTable.php

public function getEmployee($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 saveEmployee(Employee $employee) {
   $data = array (
      'emp_name' => $employee->emp_name,
      'emp_job'  => $employee->emp_job,
   );
   $id = (int) $employee->id;
   if ($id == 0) {
      $this->tableGateway->insert($data);
   } else {
      if ($this->getEmployee($id)) {
         $this->tableGateway->update($data, array('id' => $id));
      } else {
         throw new \Exception('Employee id does not exist');
      }
   }
}

ステップ20:AddActionメソッドのビュースクリプトAdd.phtmlを作成します

-myapp/module/view/employee/employeeの「Add.phtml」ファイルに次の変更を追加します。

<?php
   $title = 'Add new employee';
   $this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>

<?php
   $form->setAttribute('action', $this->url('employee', array('action' => 'add')));
   $form->prepare();
   echo $this->form()->openTag($form);
   echo $this->formHidden($form->get('id'));
   echo $this->formRow($form->get('emp_name'))."<br>";
   echo $this->formRow($form->get('emp_job'))."<br>";
   echo $this->formSubmit($form->get('submit'));
   echo $this->form()->closeTag();
Request the application using the url, http://localhost:8080/employee/add

結果

新入社員

データが追加されると、ホームページにリダイレクトされます。

リダイレクトホームページ

ステップ21:従業員レコードの編集

Employeeモジュールでデータ編集操作を実行しましょう。 Employeecontroller.php の以下の変更を更新します。

public function editAction() {
   $id = (int) $this->params()->fromRoute('id', 0);
   if (!$id) {
      return $this->redirect()->toRoute('employee', array(
         'action' => 'add'
      ));
   }
   try {
      $employee = $this->table->getEmployee($id);
   } catch (\Exception $ex) {
      return $this->redirect()->toRoute('employee', array(
         'action' => 'index'
      ));
   }
   $form = new EmployeeForm();
   $form->bind($employee);
   $form->get('submit')->setAttribute('value', 'Edit');
   $request = $this->getRequest();

   if ($request->isPost()) {
      $form->setInputFilter($employee->getInputFilter());
      $form->setData($request->getPost());
      if ($form->isValid()) {
         $this->table->saveEmployee($employee);

        //Redirect to list of employees
         return $this->redirect()->toRoute('employee');
      }
   }
   return array('id' => $id, 'form' => $form,);
}

ここでは、一致したルートにある id を探し、編集操作のために従業員の詳細をロードします。

ステップ22:Employee.php

ここで、「myapp/module/Employee/src/Employee/Model/」ディレクトリにある「Employee.php」ファイルに次の変更を追加します。

public function getArrayCopy() {
   return get_object_vars($this);
}

ここで、Zend \ Stdlib \ Hydrator \ ArraySerializableは、モデル内の2つのメソッド* getArrayCopy()および exchangeArray()*を見つけることを想定しています。

この場合、exchangeArray()が反復に使用されます。 この関数は、従業員テーブルのデータをバインドするために使用されます。

次に、* editAction()*のビュースクリプトを作成する必要があります。

ステップ23:Edit.phtmlを作成する

module/Employee/view/employee/employee/edit.phtmlにビュースクリプトファイルを作成します。

<?php
   $title = 'Edit employee records';
   $this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>

<?php
$form = $this->form;
$form->setAttribute('action', $this->url(
   'employee',
   array('action' => 'edit', 'id' => $this->id,)
));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('emp_name'))."<br>";
echo $this->formRow($form->get('emp_job'))."<br>";
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();

次のスクリーンショットに、従業員の詳細の編集を示します。

レコードの編集

データが編集されると、ホームページにリダイレクトされます。

編集済みデータ

ステップ24:deleteEmployeeメソッドを追加する

deleteEmployeeメソッドをEmployeeTableクラスに追加します– myapp/module/Employee/src/Model/EmployeeTable.php

public function deleteEmployee($id) {
   $this->tableGateway->delete(['id' => (int) $id]);
}

ステップ25:従業員レコードを削除する

Employeeモジュールでデータの削除操作を実行してみましょう。 次のメソッド deleteAction をEmployeeControllerクラスに追加します。

public function deleteAction() {
   $id = (int) $this->params()->fromRoute('id', 0);
   if (!$id) {
      return $this->redirect()->toRoute('employee');
   }
   $request = $this->getRequest();
   if ($request->isPost()) {
      $del = $request->getPost('del', 'No');
      if ($del == 'Yes') {
         $id = (int) $request->getPost('id');
         $this->table->deleteEmployee($id);
      }
      return $this->redirect()->toRoute('employee');
   }
   return array(
      'id' => $id,
      'employee' => $this->table->getEmployee($id)
   );
}

ここで、deleteEmployee()メソッドは id で従業員を削除し、従業員リストページ(ホームページ)にリダイレクトします。

deleteAction()メソッドに対応するビュースクリプトを作成しましょう。

ステップ26:ビュースクリプトを作成する

-_myapp/module/Employee/view/employee/employee/delete.phtml_にdelete.phtmlという名前のファイルを作成し、次のコードを追加します。

<?php
   $title = 'Delete an employee record';
   $this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>

'<?php echo $this->escapeHtml($employee->emp_name); ?>' by
'<?php echo $this->escapeHtml($employee->emp_job); ?&'?
<?php
   $url = $this->url('employee', array('action' => 'delete', 'id' => $this->id,));
?>

<form action ="<?php echo $url; ?>" method = "post">
   <div>
      <input type = "hidden" name = "id" value = "<?php echo (int) $employee->id; ?>"/>
      <input type = "submit" name = "del" value = "Yes"/>
      <input type = "submit" name = "del" value = "No"/>
   </div>
</form>

ここで、ホームページの edit リンクを使用して従業員を削除すると、結果は次のスクリーンショットのようになります。

結果

削除されたレコード

必要なすべての機能を実装することにより、Employeeモジュールを正常に完了しました。

結論

現在の競争環境では、Zendフレームワークは開発者によって最上位に置かれています。 PHP言語のプログラムまたはアプリケーションの種類に抽象化を提供します。 成熟したフレームワークであり、最新のPHP言語機能をサポートしています。 楽しく、プロフェッショナルで、進化し、現在のテクノロジーに歩調を合わせています。