PHPunit Ignoring getConnection() and getDataSet() - php

abstract class App_Tests_DatabaseTestCase extends PHPUnit_Extensions_Database_TestCase {
protected $App;
/**
* #return PHPUnit_Extensions_Database_DB_IDatabaseConnection
*/
public function log($text)
{
$file = '/Applications/MAMP/htdocs/zumba/app/vendors/billing/tests/abstract/log.txt';
$current = file_get_contents($file);
$current .= $text."\n";
file_put_contents($file, $current);
}
final public function getConnection()
{
$this->log("Initiate Get Connection");
$this->App = new App();
if ($this->conn === null) {
if (self::$pdo == null) {
self::$pdo = new PDO( $GLOBALS['DB_DSN'], $GLOBALS['DB_USER'], $GLOBALS['DB_PASSWD'] );
}
$this->conn = $this->createDefaultDBConnection(self::$pdo, $GLOBALS['DB_DBNAME']);
}
return $this->conn;
}
protected function getDataSet()
{
$this->log("Initiate GetDataSet");
return new ZumbaDbUnitArrayDataSet(array(
'guestbook' => array(
array('id' => 1, 'content' => 'Hello buddy!', 'user' => 'joe', 'created' => '2010-04-24 17:15:23'),
array('id' => 2, 'content' => 'I like it!', 'user' => null, 'created' => '2010-04-26 12:14:20'),
),
));
}
protected function setUp() {
$this->log("Initiate Setup");
$this->App = new App();
}
protected function tearDown() {
$this->log("Initiate Tear Down");
unset($this->App);
}
}
I added a log to keep track of progress but same outcome
Below is Output
Configuration read from
F Initiate Setup Initiate Tear Down
Time: 0 seconds, Memory: 6.25Mb
There was 1 failure:
1) BillingControlTest::test_funrun
Failed asserting that false is true.
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
I execute this file
class BillingControlTest extends App_Tests_DatabaseTestCase {
function test_funrun()
{
$returnVal = $this->App->query("UPDATE guestbook SET created = NOW() WHERE id = 1");
$this->assertTrue($returnVal);
}
}
As you can see. it runs through the setup and tearDown but skips getConnection and getDataset. I am following the tutorial on the website.

Related

Fatal error: Uncaught Error: Non-static method primaryKey() cannot be called statically [duplicate]

This question already has answers here:
Error message Strict standards: Non-static method should not be called statically in php
(7 answers)
Closed 1 year ago.
how can I fix this error?
Fatal error: Uncaught Error: Non-static method thecodeholic\phpmvc\db\DbModel::primaryKey() cannot be called statically in C:\xampp\htdocs\php-mvc-framework-master\vendor\thecodeholic\php-mvc-core\Application.php:53 Stack trace: #0 C:\xampp\htdocs\php-mvc-framework-master\public\index.php(25): thecodeholic\phpmvc\Application->__construct('C:\\xampp\\htdocs...', Array) #1 {main} thrown in C:\xampp\htdocs\php-mvc-framework-master\vendor\thecodeholic\php-mvc-core\Application.php on line 53
here is my index.php in public folder:
<?php
/**
* User: TheCodeholic
* Date: 7/7/2020
* Time: 9:57 AM
*/
use app\controllers\AboutController;
use app\controllers\SiteController;
use thecodeholic\phpmvc\Application;
require_once __DIR__ . '/../vendor/autoload.php';
$dotenv = \Dotenv\Dotenv::createImmutable(dirname(__DIR__));
$dotenv->load();
$config = [
'userClass' => \app\models\User::class,
'db' => [
'dsn' => $_ENV['DB_DSN'],
'user' => $_ENV['DB_USER'],
'password' => $_ENV['DB_PASSWORD'],
]
];
$app = new Application(dirname(__DIR__), $config);
$app->on(Application::EVENT_BEFORE_REQUEST, function(){
echo "Before request from second installation";
});
$app->router->get('/', [SiteController::class, 'home']);
...
$app->run();
and here is Application.php code:
<?php
/**
* User: TheCodeholic
* Date: 7/7/2020
* Time: 9:57 AM
*/
namespace thecodeholic\phpmvc;
use thecodeholic\phpmvc\db\Database;
/**
* Class Application
*
* #author Zura Sekhniashvili <zurasekhniashvili#gmail.com>
* #package app
*/
class Application
{
const EVENT_BEFORE_REQUEST = 'beforeRequest';
const EVENT_AFTER_REQUEST = 'afterRequest';
protected array $eventListeners = [];
public static Application $app;
public static string $ROOT_DIR;
public string $userClass;
public string $layout = 'main';
public Router $router;
public Request $request;
public Response $response;
public ?Controller $controller = null;
public Database $db;
public Session $session;
public View $view;
public ?UserModel $user;
public function __construct($rootDir, $config)
{
$this->user = null;
$this->userClass = $config['userClass'];
self::$ROOT_DIR = $rootDir;
self::$app = $this;
$this->request = new Request();
$this->response = new Response();
$this->router = new Router($this->request, $this->response);
$this->db = new Database($config['db']);
$this->session = new Session();
$this->view = new View();
$userId = Application::$app->session->get('user');
if ($userId) {
$key = $this->userClass::primaryKey();
$this->user = $this->userClass::findOne([$key => $userId]);
}
}
public static function isGuest()
{
return !self::$app->user;
}
public function login(UserModel $user)
{
$this->user = $user;
$primaryKey = $user->primaryKey();
$value = $user->{$primaryKey};
Application::$app->session->set('user', $value);
return true;
}
public function logout()
{
$this->user = null;
self::$app->session->remove('user');
}
public function run()
{
$this->triggerEvent(self::EVENT_BEFORE_REQUEST);
try {
echo $this->router->resolve();
} catch (\Exception $e) {
echo $this->router->renderView('_error', [
'exception' => $e,
]);
}
}
public function triggerEvent($eventName)
{
$callbacks = $this->eventListeners[$eventName] ?? [];
foreach ($callbacks as $callback) {
call_user_func($callback);
}
}
public function on($eventName, $callback)
{
$this->eventListeners[$eventName][] = $callback;
}
}
$key = $this->userClass->primaryKey();
$this->user = $this->userClass->findOne([$key => $userId]);
i think the function primaryKey and findOne will be normal public and not static in your Entity.
class UserClass {
public function primaryKey() {
....
}
public function findOne() {
...
}
}
so you has to use -> instead of :: to call the methods

How to keep php://stdout open forever

I find a bug with php integrated to Ejabberd in authentication mode. This script, open php://stdin and php://stdout to read/write data, but after a while it will be hang so the authentication feature could not work.
My code:
<?php
/**
* A class extending EjabberdExternalAuth may optionally implement this interface
* to support additional, non-critical methods for adding and removing users.
*/
interface EjabberdExternalAuth_UserManagement {
/**
* Corresponds to `setpass` operation.
*/
public function setPassword($user, $server, $password);
/**
* Corresponds to `tryregister` operation.
*/
public function register($user, $server, $password);
/**
* Corresponds to `removeuser` operation.
*/
public function remove($user, $server);
/**
* Corresponds to `removeuser3` operation.
*/
public function removeSafely($user, $server, $password);
}
abstract class EjabberdExternalAuth {
private $db = null;
private $log = null;
private $stdin = null;
private $stdout = null;
public static $logLevel = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_INFO, LOG_KERN);
/**
* Corresponds to `auth` operation.
*/
abstract protected function authenticate($user, $server, $password);
/**
* Corresponds to `isuser` operation.
*/
abstract protected function exists($user, $server);
final public function __construct(PDO $db = null, $log = null) {
set_error_handler(array($this, 'errorHandler'));
$this->db = $db;
$this->stdin = fopen('php://stdin', 'rb');
$this->stdout = fopen('php://stdout', 'wb');
if ($log) {
$this->log = fopen($log, 'a');
}
$this->log('Starting auth service...', LOG_INFO);
try {
$this->work();
} catch (Exception $e) {
$this->log($e->getMessage());
}
$this->log('Exiting...', LOG_INFO);
}
final protected function db() {
return $this->db;
}
final private function work() {
$this->log('Entering event loop...', LOG_INFO);
while (true) {
try {
$message = $this->read();
$message = $this->parseMessage($message);
} catch (UnexpectedValueException $e) {
$this->log($e->getMessage());
continue;
}
$this->log('Received message: ' . json_encode($message), LOG_DEBUG);
$response = false;
switch ($message['command']) {
case 'auth' :
$response = $this->authenticate($message['user'], $message['server'], $message['password']);
break;
case 'isuser' :
$response = $this->exists($message['user'], $message['server']);
break;
}
if ($this instanceof EjabberdExternalAuth_UserManagement) {
switch ($message['command']) {
case 'setpass' :
$response = $this->setPassword($message['user'], $message['server'], $message['password']);
break;
case 'tryregister' :
$response = $this->register($message['user'], $message['server'], $message['password']);
break;
case 'removeuser' :
$response = $this->remove($message['user'], $message['server']);
break;
case 'removeuser3' :
$response = $this->removeSafely($message['user'], $message['server'], $message['password']);
break;
}
}
$this->respond($response);
}
}
final private function read() {
$length = fgets($this->stdin, 3);
if (feof($this->stdin)) {
throw new RuntimeException('Pipe broken');
}
$length = current(unpack('n', $length));
if (!$length) {
throw new UnexpectedValueException("Invalid length value, won't continue reading");
}
$message = fgets($this->stdin, $length + 1);
return $message;
}
final private function parseMessage($message) {
$message = explode(':', $message, 4);
if (count($message) < 3) {
throw new UnexpectedValueException('Message is too short: ' . join(':', $message));
}
list($command, $user, $server) = $message;
$password = isset($message[3]) ? $message[3] : null;
return compact('command', 'user', 'server', 'password');
}
final private function respond($status) {
$message = pack('nn', 2, (int)$status);
$this->log('Sending response: ' . bin2hex($message), LOG_DEBUG);
fwrite($this->stdout, $message);
}
final protected function log($message, $severity = LOG_ERR) {
if ($this->log && in_array($severity, self::$logLevel, true)) {
static $types = array(
LOG_EMERG => 'EMERGENCY',
LOG_ALERT => 'ALERT',
LOG_CRIT => 'CRITICAL',
LOG_ERR => 'ERROR',
LOG_WARNING => 'WARNING',
LOG_NOTICE => 'NOTICE',
LOG_INFO => 'INFO',
LOG_DEBUG => 'DEBUG',
LOG_KERN => 'KERNEL'
);
$message = sprintf('%s <%s> %9s: %s', date('Y-m-d H:i:s'), getmypid(), isset($types[$severity]) ? $types[$severity] : $types[LOG_ERR], $message);
fwrite($this->log, $message . PHP_EOL);
}
}
final protected function errorHandler($errno, $errstr, $errfile, $errline, array $errcontext) {
$this->log("($errno) $errstr in $errfile on line $errline");
return false;
}
}
I think that, something is wrong, example: the STDOUT may be broken, so I need to write data to php://stdout forever, so how could I make sure the stream will never be broken.

phpunit dbunit #dataProvider doesn't work

I spent a lot of time by searching where is the problem, but i haven't find anything.
It sais "testAdd caused an ERROR: Missing argument". Simply the dataProvider isn't executed, when I run the test. I tried to put die() into the dataProvider and it hasn't died.
This is my code:
class LabelEntityModelTest extends PHPUnit_Extensions_Database_TestCase
{
private static $connection = NULL;
/**
* #var \CXNS\DB\Connections\Connection
*/
private static $appConnection;
private static $table;
public function __construct()
{
if (self::$connection) {
return;
}
$pdo = new \PDO($GLOBALS['DB_DSN'], $GLOBALS['DB_USER'], $GLOBALS['DB_PASSWD']);
self::$appConnection = new \CXNS\DB\Connections\Connection(array("prefix" => "test_", "driver" => "pdo", "resource" => $pdo));
self::$appConnection->connect();
self::$connection = $this->createDefaultDBConnection($pdo, 'mysql');
self::$table = $this->createXMLDataSet(__DIR__ . '/fixtures/tables.xml');
}
protected function getDataSet()
{
return self::$table;
}
public function getConnection()
{
return self::$connection;
}
public function getAppConnection()
{
return self::$appConnection;
}
/**
* #group onlyThis
* #dataProvider providerAdd
*/
public function testAdd($labelId, $entityId)
{
$lem = new \appLibs\Labels\LabelEntityModel($this->getAppConnection(), "contacts");
$lem->add($labelId, $entityId);
$count = $this->getAppConnection()
->select("id")
->from("label_relationships")
->where("label_id = %i", $labelId)
->where("table_ref_id = %i", $entityId)
->count();
$this->assertEquals(1, $count, "insert failed");
}
public function providerAdd()
{
return array(
array(2, 3),
array(3, 4),
array(3, 4),
array(3, 4),
array(3, 4),
array(3, 4),
array(5, 7)
);
}
}
Thank you for your help.
You should never overwrite TestCase constructor.
PhpUnit has a specialized methods for initialization purposes called setUp and setUpBeforeClass, so I strongly suggest you to use that.
I´m pretty sure this is the cause of your problem.

ZF2 ServiceLocatorAwareInterface getServiceLocator gives me the Zend\Validator\ValidatorPluginManager

For my ZF2 form validation I need the entity manager in my custom validator. I Zend\ServiceManager\ServiceLocatorAwareInterface to get the service locator in my validator so I would be able to get the entitymanager from there.
My problem is that this Zend\ServiceManager\ServiceLocatorAwareInterface::setServiceLocator injects the "Zend\Validator\ValidatorPluginManager" and not the desired ServiceLocator.
Does anybody know how to solve this problem?
My abstract controller
abstract class AbstractController extends AbstractActionController
{
/**
* This property contains the doctrine entitymanager.
* #var Doctrine\ORM\EntityManager
*/
protected $_entityManager;
/**
* This method returns the doctrine entitymanager.
* #return \Doctrine\ORM\EntityManager
*/
public function getEntityManager()
{
var_dump(spl_object_hash($this->getServiceLocator())); echo '<br>';
if (null === $this->_entityManager)
$this->_entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
return $this->_entityManager;
}
}
My validator:
class EntityUnique extends AbstractValidator implements ServiceLocatorAwareInterface
{
protected $_serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
var_dump(spl_object_hash($serviceLocator)); echo '<br>';
$this->_serviceLocator = $serviceLocator;
}
function getServiceLocator()
{
return $this->_serviceLocator;
}
}
When executing this both var_dumps result in another object hash:
string(32) "000000005e4258390000000024a7f829"
string(32) "000000005e425a2d0000000024a7f829"
The reason for this is that in your validator you are getting the Zend\Validator\ValidatorPluginManager injected. If you want the the Service Manager call getServiceLocator on the Zend\Validator\ValidatorPluginManager.
For example look at the someMethod() method bellow:
class EntityUnique extends AbstractValidator implements ServiceLocatorAwareInterface
{
protected $_serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
var_dump(spl_object_hash($serviceLocator)); echo '<br>';
$this->_serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->_serviceLocator;
}
public function someMethod()
{
$validatorPluginManager = $this->getServiceLocator();
$serviceLocator = $validatorPluginManager->getServiceLocator(); // HERE
}
}
Hope this helps :)
Stoyan
I got it working in the end. I don't know if this is the best practice so if you have any feedback don't hesitate. My validator ended up like this:
<?php
namespace Flex\Validator;
use Doctrine\ORM\EntityManager;
use Zend\Stdlib\ArrayUtils;
use Zend\ServiceManager\ServiceManager;
use Zend\Validator\AbstractValidator;
class EntityUnique extends AbstractValidator
{
const EXISTS = 'exists';
protected $messageTemplates = array(
self::EXISTS => 'A %entity% entity allready exists.',
);
protected $messageVariables = array(
'entity' => '_entity',
);
protected $_context;
protected $_entity;
protected $_excludes = array();
protected $_filters = array();
protected $_property;
protected $_serviceLocator;
public function __construct($options = null)
{
if ($options instanceof \Traversable)
$options = ArrayUtils::iteratorToArray($options);
if (is_array($options))
{
if (isset($options['entity']))
$this->_entity = $options['entity'];
if (isset($options['exclude']))
{
if (!is_array($options['exclude']))
throw new \Exception('Exclude option should be an array');
if (isset($options['exclude']['property']) && isset($options['exclude']['value']))
$this->_excludes[] = array(
'property' => $options['exclude']['property'],
'value' => $options['exclude']['value'],
);
else
foreach ($options['exclude'] as $exclude)
{
if (!isset($exclude['property']) || !isset($exclude['value']))
throw new \Exception('exclude shoud contain a property and value');
$this->_excludes[] = array(
'property' => $exclude['property'],
'value' => $exclude['value'],
);
}
}
if (isset($options['filter']))
{
if (!is_array($options['filter']))
throw new \Exception('Filter option should be an array');
if (isset($options['filter']['property']) && isset($options['filter']['value']))
$this->_filters[] = array(
'property' => $options['filter']['property'],
'value' => $options['filter']['value'],
);
else
foreach ($options['filter'] as $filter)
{
if (!isset($filter['property']) || !isset($filter['value']))
throw new \Exception('Filters shoud contain a property and value');
$this->_filters[] = array(
'property' => $filter['property'],
'value' => $filter['value'],
);
}
}
if (isset($options['property']))
$this->_property = $options['property'];
if (!isset($options['serviceLocator']))
throw new \InvalidArgumentException(__CLASS__ . ' requires the option serviceLocator.');
$ServiceManagerInstance = 'Zend\ServiceManager\ServiceManager';
if (!($options['serviceLocator'] instanceof $ServiceManagerInstance))
throw new \InvalidArgumentException(__CLASS__ . ' expects the option serviceLocator to be an instance of Zend\ServiceManager\ServiceManager.');
$this->_serviceLocator = $options['serviceLocator'];
}
parent::__construct(is_array($options) ? $options : null);
}
public function isValid($value, $context = null)
{
$this->setValue($value);
$this->_context = $context;
$entityManager = $this->_serviceLocator->get('doctrine.entitymanager.orm_default');
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder->from($this->_entity, 'e')
->select('COUNT(e)')
->where('e.' . $this->_property . ' = :value')
->setParameter('value', $this->getValue());
if (count($this->_excludes))
foreach ($this->_excludes as $key => $exclude)
{
$exclude['value'] = $this->parse($exclude['value']);
if ($exclude['value'] !== null)
$queryBuilder->andWhere('e.' . $exclude['property'] . ' = :exclude_' . $key)
->setParameter('exclude_' . $key, $exclude['value']);
else
$queryBuilder->andWhere('e.' . $exclude['property'] . ' IS NULL');
}
if (count($this->_filters))
foreach ($this->_filters as $key => $filter)
{
$filter['value'] = $this->parse($filter['value']);
if ($filter['value'] !== null)
$queryBuilder->andWhere('e.' . $filter['property'] . ' = :filter_' . $key)
->setParameter('filter_' . $key, $filter['value']);
else
$queryBuilder->andWhere('e.' . $filter['property'] . ' IS NULL');
}
$query = $queryBuilder->getQuery();
if ((integer) $query->getSingleScalarResult() !== 0)
{
$this->error(self::EXISTS);
return false;
}
return true;
}
private function parse($input, $current = null)
{
if (!is_array($input))
return $input;
if ($current === null)
$current = $this;
$currentKey = array_shift($input);
if (is_object($current) && property_exists($current, $currentKey))
$current = $current->$currentKey;
elseif (is_array($current) && array_key_exists($currentKey, $current))
$current = $current[$currentKey];
else
return null;
if (count($input))
return $this->parse($input, $current);
if (strlen($current) == 0)
return null;
return $current;
}
}
This is loaded in like this:
<?php
namespace FlexCategories\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class CategoryForm extends Form implements InputFilterProviderInterface, ServiceManagerAwareInterface
{
private $_serviceManager;
public function init()
{
/* */
}
public function getInputFilterSpecification()
{
return array(
'name' => array(
'filters' => array(
array(
'name' => 'Zend\Filter\StringTrim'
),
),
'required' => true,
'validators' => array(
array(
'name' => 'Flex\Validator\EntityUnique',
'options' => array(
'entity' => 'FlexCategories\Entity\Category',
'filter' => array(
array('property' => 'parent',
'value' => array('_context', 'parent')),
),
'property' => 'name',
'serviceLocator' => $this->_serviceManager,
),
),
),
),
);
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->_serviceManager = $serviceManager;
$this->init();
return $this;
}
}
The form is registered in the service_manager => invokables and is retreived within the controller thorugh the service manager.
This worked for me. I hope somebody will be able to learn from this or give me feedbacl to create an better solution.

Zend_Log_Writer_Db - Call to undefined method Zend_Config::insert()

I am running php 5.2.12 and Zend Framework 5.0.2
In my Bootstrap.php, I initialize our database connection, and initialize our logger... placing both in the registry.
However, when I try to log info in the IndexController.php, it gives the following message:
"*Fatal error: Call to undefined method Zend_Config::insert() in /usr/local/zendsvr/share/ZendFramework/library/Zend/Log/Writer/Db.php on line 137*"
At the bottom of this post, you will find the Zend Framework's class file, db.php , and the _write function being called.
I believe the problem is that I am getting the database connection options from my application.ini... and there is no insert() function defined in my application.ini for the database. But I dont really know how to add one to the config, or how I should be doing this.
Bootstrap.php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initConfig()
{
Zend_Registry::set('config', new Zend_Config($this->getOptions()));
}
protected function _initDatabases()
{
$this->bootstrap('multidb');
$resource = $this->getPluginResource('multidb');
$databases = Zend_Registry::get('config')->resources->multidb;
foreach ($databases as $name => $adapter)
{
$db_adapter = $resource->getDb($name);
Zend_Registry::set($name, $db_adapter);
}
}
protected function _initLog()
{
$db = Zend_Registry::get('config')->resources->multidb->as400;
$columnMapping = array('ILGID' => 'id', //1 numeric
'ILGLVL' => 'priority', //2 numeric
'ILGDTE' => 'date', //yymmdd
'ILGTME' => 'time', //hhmmss
'ILGPGM' => 'program', //40 alnum
'ILGURL' => 'url', //2100
'ILGUSR' => 'user', //30
'ILGMSG' => 'message'); //1000
$writer = new Zend_Log_Writer_Db($db, 'dwhlib.intralog', $columnMapping);
$logger = new Zend_Log($writer);
$date = new Zend_Date();
date_default_timezone_set('America/Chicago');
$logger->setEventItem('id' , 1);
$logger->setEventItem('date' , $date->get('Ymd'));
$logger->setEventItem('time' , $date->get('Hms'));
$logger->setEventItem('program' , 'testProgramName'); $logger->setEventItem('url' , $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
$logger->setEventItem('user' , gethostbyaddr($_SERVER['REMOTE_ADDR']));
Zend_Registry::set('logger', $logger);
}
}
application.ini
resources.multidb.as400.adapter = "db2"
resources.multidb.as400.host = "i5"
resources.multidb.as400.username = "removedUsername"
resources.multidb.as400.password = "removedPassword"
resources.multidb.as400.dbname = "*LOCAL"
resources.multidb.as400.default = true
IndexController.php
include("/www/zendserver/htdocs/development/application/models/as400.php");
class IndexController extends Zend_Controller_Action
{
public function init()
{
Zend_Registry::get('logger')->info("this is a test message");
}
public function indexAction()
{
// action body
}
}
as400.php
Class default_Model_As400 extends Zend_Db {
public static function ExecuteSelect($sql, $mode = Zend_Db::FETCH_ASSOC, $log = false)
{
$stmt = self::getStmt($sql);
$stmt->setFetchMode($mode);
$stmt->execute();
if($log === true) {
Zend_Registry::get('logger')->info($sql);
}
$rows = $stmt->fetchAll();
return $rows;
}
private static function getStmt($sql){
$db = Zend_Registry::get('config')->resources->multidb->as400;
$abstractAdapter = new Zend_Db_Adapter_Db2($db);
return new Zend_Db_Statement_DB2($abstractAdapter, $sql);
}
public function insert($libAndFile, $arrData){
echo "this was hit!!";
}
}
db.php
class Zend_Log_Writer_Db extends Zend_Log_Writer_Abstract
{
public function __construct($db, $table, $columnMap = null)
{
$this->_db = $db;
$this->_table = $table;
$this->_columnMap = $columnMap;
}
protected function _write($event)
{
if ($this->_db === null) {
require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Database adapter is null');
}
if ($this->_columnMap === null) {
$dataToInsert = $event;
} else {
$dataToInsert = array();
foreach ($this->_columnMap as $columnName => $fieldKey) {
$dataToInsert[$columnName] = $event[$fieldKey];
}
}
$this->_db->insert($this->_table, $dataToInsert);
}
}
What is happening: you are calling a method called insert() on a Zend_Config instance.
What you want: call a method insert() through a Zend_Db_Adapter.
There is something wrong in your _initLog() bootstrap method:
$db = Zend_Registry::get('config')->resources->multidb->as400;
$writer = new Zend_Log_Writer_Db($db, 'dwhlib.intralog', $columnMapping);
Zend_Log_Writer_Db expects a Zend_Db adapter as a first constructor parameter. To fix this, since you already registered your database adapter in the registry, you should do something like this :
$dbName = Zend_Registry::get('config')->resources->multidb->as400;
$db = Zend_Registry::get($dbName);
$writer = new Zend_Log_Writer_Db($db, 'dwhlib.intralog', $columnMapping);

Categories