简体   繁体   中英

using Zend_Db zf2 module outside of zf2 mvc

I'm writing a PHP application that is not based on zf2 mvc.

I do want to use only the Zend_Db zf2 module. how can I configure my application to know how to find the Zend_Db releveant PHP file where required ?

I have zf2 Zend_db module download with phyrus and installed at the location 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/ .

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:

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 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 ?

maybe is there another zf2 component I can use that will autoload the relevant classes?

From what I see from your code, you don't include anywhere the files corresponding to the necessary classes (eg. 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. 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 :

{
    "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 will generate you the auto-loading file vendor/autoload.php that you can include for automatically loading your dependencies classes.

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)

This is not my work, but Abdul Malik Ikhsan (ZF2 contributor) has a great blog post about using Zend/DB as a standalone component.

Like @yechabbi mentioned, you'll probably do yourself a lot of good to use Composer as your dependency manager.

It looks like you might be stumbling with where you're placing Zend-Db and what you're naming it. For example, in my working ZF2 installation, the Zend_Db component is located in 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:

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

Abdul then uses the following namespaces in his Table class

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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