简体   繁体   English

在zf2 mvc之外使用Zend_Db zf2模块

[英]using Zend_Db zf2 module outside of zf2 mvc

I'm writing a PHP application that is not based on zf2 mvc. 我正在编写一个不基于zf2 mvc的PHP应用程序。

I do want to use only the Zend_Db zf2 module. 我想只使用Zend_Db zf2模块。 how can I configure my application to know how to find the Zend_Db releveant PHP file where required ? 如何配置我的应用程序以了解如何在需要时找到Zend_Db相关的PHP文件?

I have zf2 Zend_db module download with phyrus and installed at the location vendor/zf2/php . 我有zr2 Zend_db模块下载与phyrus并安装在vendor/zf2/php的位置。

I tried adding the module to the include path with the following command: 我尝试使用以下命令将模块添加到包含路径:

set_include_path("../vendor/zf2/php".PATH_SEPARATOR.get_include_path());

I created Model class files relevant to each table (using zend-db-model-generator) inside directory Model/ . 我在目录Model/创建了与每个​​表相关的Model类文件(使用zend-db-model-generator)。

my main app contains the following: 我的主应用程序包含以下内容:

use DrinkManagement\Model\DrinkTable;
use Zend\Db\Adapter\Adapter;


set_include_path("../vendor/zf2/php".PATH_SEPARATOR.get_include_path());

require_once('Model/DrinkTable.php');

/**
 @var DrinkManagement\Model\Drink
 */
$drinkTable=null;

$drinkTable = new DrinkTable();
$res=$drinkTable->getDrink(1);
echo var_export($res,1);

my DrinkTable class: 我的DrinkTable类:

namespace DrinkManagement\Model;

use Zend\Db\TableGateway\AbstractTableGateway,

class DrinkTable extends AbstractTableGateway
{
protected $table ='drink';
protected $tableName ='drink';

public function __construct(Adapter $adapter)
{
    $this->adapter = $adapter;
    $this->resultSetPrototype = new ResultSet(new Drink);

    $this->initialize();
}

public function fetchAll()
{
    $resultSet = $this->select();
    return $resultSet;
}

public function newSelect() {
    return new Select;
}

public function getSelect(&$select,$columnsArray=array()) 
{
    $select = new Select;
    return $select->from('drink')->columns($columnsArray);      
}

public function createIfNotExist($checkColumnsArray,$optionalColumns=array(),&$isRowCreated=null) {
        $rowset=$this->select($checkColumnsArray);
        $row = $rowset->current();
        $id=null;
        if ($row == null) {
            $allColumns=array_merge($checkColumnsArray,$optionalColumns);
            $affectedRows = $this->insert($allColumns);
            if ($affectedRows != 1) {
                throw new \Exception("error: could not add line to db");
            }
            $id=$this->lastInsertValue;
            $isRowCreated=true;
        } else {
            $id=$row->drink_id;
            $isRowCreated=false;
        }
        return $id;
}

//http://stackoverflow.com/questions/6156942/how-do-i-insert-an-empty-row-but-have-the-autonumber-update-correctly

public function createEmptyRow() {
    $row=array(
    'drink_id' => null
    );
    $affectedRows=$this->insert($row);
    if ($affectedRows != 1) {
        throw new \Exception("error: could not add empty row to db");
    }
    $id=$this->lastInsertValue;
    return $id;
}

public function getDrink($id)
{
    $id  = (int) $id;
    $rowset = $this->select(array('drink_id' => $id));
    $row = $rowset->current();
    if (!$row) {
        throw new \Exception("Could not find row $id");
    }
    return $row;
}

public function saveDrink(Drink $drink)
{
    $data = array(
                    'drink_type_id' => $drink->drink_type_id,
                    'drink_brand_id' => $drink->drink_brand_id,
                    'creation_timestamp' => $drink->creation_timestamp,
                );

    $id = (int)$drink->id;
    if ($id == 0) {
        $this->insert($data);
    } else {
        if ($this->getDrink($id)) {
            $this->update($data, array('drink_id' => $id));
        } else {
            throw new \Exception('Form id does not exit');
        }
    }
}

public function addDrink($drink_type_id, $drink_brand_id = null, $creation_timestamp = null)
{
    $data = array(            'drink_type_id' => $drink_type_id,
                    'drink_brand_id' => $drink_brand_id,
                    'creation_timestamp' => $creation_timestamp,
                );
    $affectedRows=$this->insert($data);
            if ($affectedRows != 1) {
        return null;
    }
    return $this->lastInsertValue;
        }

public function updateDrink($drink_id, $drink_type_id, $drink_brand_id, $creation_timestamp)
{
    $data = array(
                    'drink_type_id' => $drink->drink_type_id,
                    'drink_brand_id' => $drink->drink_brand_id,
                    'creation_timestamp' => $drink->creation_timestamp,
                        );
    $this->update($data, array(drink_id => $id));
}

public function deleteDrink($id)
{
    $this->delete(array('drink_id' => $id));
}

}

when I try to execute my main php application i get the following error message: 当我尝试执行我的主要PHP应用程序时,我收到以下错误消息:

PHP Fatal error:  Class 'Zend\Db\TableGateway\AbstractTableGateway' not found in /Users/ufk/Documents/workspace/tux-drink/TuxDb/mysql/Model/DrinkTable.php on line 10

any ideas how to resolve the issue without adding require_once everywhere ? 任何想法如何解决问题,而无需在任何地方添加require_once?

maybe is there another zf2 component I can use that will autoload the relevant classes? 也许还有我可以使用的另一个zf2组件会自动加载相关的类吗?

From what I see from your code, you don't include anywhere the files corresponding to the necessary classes (eg. AbstractTableGateway). 从我从您的代码中看到的,您不包含与必要类相对应的文件(例如,AbstractTableGateway)。 Setting the vendor path as an include path won't solve your problem. 将供应商路径设置为包含路径不会解决您的问题。

Trying to add manually your dependencies will cause you many troubles as you'll have not only to add manually your dependecies for the classes you are using but also for the their dependencies (Adapters, Drivers etc.) 尝试手动添加依赖项会给您带来许多麻烦,因为您不仅要为您正在使用的类手动添加您的依赖项,还要为它们的依赖项(适配器,驱动程序等)添加。

In my opinion, It would be better for you to use a dependency manager such as Composer for managing your dependencies & their auto-loading. 在我看来,最好使用Composer之类的依赖管理器来管理依赖关系及其自动加载。 You can actually define a dependency for the zendframework\\zend-db package within the composer.json (which you have to create at the root project directory) as follows : 实际上,您可以在composer.json(必须在根项目目录中创建)中为zendframework \\ zend-db包定义依赖项,如下所示:

{
    "name": "Your project name",
    "description": "Your project description",
    "autoload": {
        "psr-0": {
            "Zend\\Db\\": ""
        }
    },
    "target-dir": "Zend/Db",
    "repositories": [
                {
                    "type": "composer",
                    "url": "https://packages.zendframework.com/"
                }
            ],
    "require": {
        "php": ">=5.3.3",
        "zendframework/zend-db":"2.0.*"
    }
}

After installing composer to your project folder, run php composer.phar install from your command line. 将composer安装到项目文件夹后,从命令行运行php composer.phar install Composer will generate you the auto-loading file vendor/autoload.php that you can include for automatically loading your dependencies classes. Composer将为您生成自动加载文件vendor/autoload.php ,您可以包含该文件以自动加载依赖项类。

Example: 例:

<?php

// Always include autoload files when using vendor classes
include 'vendor/autoload.php';
require_once('Model/DrinkTable.php');

use DrinkManagement\Model\DrinkTable;
use Zend\Db\Adapter\Adapter;

//Don't forget declaring an adapter

$adapter = new Adapter(array(
        'driver' => 'Mysqli',
        'database' => 'test',
        'username' => 'dev',
        'password' => 'dev'
     ));
//Your constructor should include the adapter
$drinkTable = new DrinkTable('drinktable', $adapter);

//Do necessary stuff with the table
//....


echo var_export($res,1);


?>

Note: You can declare a dependency for zend-loader, so that you can use Zend\\Loader\\StandardAutoloader for auto-loading your own classes (assuming you're using PSR-0) 注意:您可以为zend-loader声明一个依赖项,以便您可以使用Zend \\ Loader \\ StandardAutoloader自动加载您自己的类(假设您使用的是PSR-0)

This is not my work, but Abdul Malik Ikhsan (ZF2 contributor) has a great blog post about using Zend/DB as a standalone component. 这不是我的工作,但是Abdul Malik Ikhsan(ZF2撰稿人)有一篇关于使用Zend / DB作为独立组件的博文

Like @yechabbi mentioned, you'll probably do yourself a lot of good to use Composer as your dependency manager. 就像@yechabbi提到的那样,使用Composer作为依赖管理器你可能会做很多好事。

It looks like you might be stumbling with where you're placing Zend-Db and what you're naming it. 看起来你可能会绊倒你放置Zend-Db的地方以及你命名它的地方。 For example, in my working ZF2 installation, the Zend_Db component is located in vendor/zendframework/zendframework/library/Zend/Db. 例如,在我工作的ZF2安装中,Zend_Db组件位于vendor / zendframework / zendframework / library / Zend / Db中。 Using Composer with the correct require statements as Abdul quotes in his blog post should take care of all that for you: 在他的博客文章中使用具有正确需求语句的Composer作为Abdul引用应该照顾所有这些:

"require": {
    "php": ">=5.3.3",
    "zendframework/zend-db": "2.*",
    "zendframework/zend-stdlib": "2.*"
}

Abdul then uses the following namespaces in his Table class 然后Abdul在他的Table类中使用以下命名空间

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Zend\Db\ResultSet\HydratingResultSet;

I don't know that this will fix all of your issues but it will get you on the right track I hope. 我不知道这会解决你所有的问题,但它会让你走上正确的轨道我希望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM