I'm using Woocommerce with my Wordpress theme. The website is selling services. The template developer support is dead, they say woocommerce compatibility but there is small bug I need to find the fix myself but I don't know what to do.
When the client tries to add credit to his account he selects the value and goes to next screen where woocommerce payment gateways are shown, they are listed but 'Pay' button its not there. When I look into Wordpress wp-content debug log I got this errors:
[23-Jul-2018 10:15:58 UTC] PHP Strict Standards: Declaration of ET_WC_Order::get_total() should be compatible with WC_Abstract_Order::get_total($context = 'view') in /home/admin/public_html/mysite.com/wp-content/themes/mysite.com/includes/aecore/wc_integration/payment/ET_WC_Order.php on line 3
[23-Jul-2018 10:15:58 UTC] PHP Strict Standards: Declaration of ET_WC_Package::get_sku() should be compatible with WC_Product::get_sku($context = 'view') in /home/admin/public_html/mysite.com/wp-content/themes/mysite.com/includes/aecore/wc_integration/payment/ET_WC_Package.php on line 4
ET_WC_Order.php content:
<?php if(class_exists("WC_Abstract_Order")) {
class ET_WC_Order extends WC_Abstract_Order
{
protected $etOrder;
protected $cancel_url = "";
protected $received_url = "";
public function __construct($order = '')
{
$this->post_type = 'order';
$this->prices_include_tax = get_option('woocommerce_prices_include_tax') == 'yes' ? true : false;
$this->tax_display_cart = get_option('woocommerce_tax_display_cart');
$this->display_totals_ex_tax = $this->tax_display_cart == 'excl' ? true : false;
$this->display_cart_ex_tax = $this->tax_display_cart == 'excl' ? true : false;
$this->init($order);
}
public function get_refunds()
{
return array();
}
public function get_total_refunded()
{
return 0;
}
/**
* Init
*
* #param int|object|WC_Order $order
*/
protected function init($order)
{
if (is_numeric($order)) {
$this->id = absint($order);
$this->post = get_post($order);
$this->get_order($this->id);
} elseif ($order instanceof ET_WC_Order) {
$this->id = absint($order->id);
$this->ID = absint($order->id);
$this->post = $order->post;
$this->etOrder = $order->etOrder;
$this->populate($order->etOrder);
} elseif ($order instanceof AE_Order) {
$payData = $order->generate_data_to_pay();
$order->ID = $payData["ID"];
$this->etOrder = $order;
$this->populate($order);
// Billing email cam default to user if set
if (empty($this->billing_email) && !empty($this->customer_user)) {
$user = get_user_by('id', $this->customer_user);
$this->billing_email = $user->user_email;
}
} elseif ($order instanceof WP_Post || isset($order->ID)) {
$this->id = absint($order->ID);
$this->post = $order;
$this->get_order($this->id);
}
}
public function get_order($id = 0)
{
if (!$id) {
return false;
}
$this->etOrder = new AE_Order($id);
if ($this->etOrder) {
$payData = $this->etOrder->generate_data_to_pay();
$this->etOrder->ID = $payData["ID"];
$this->populate($this->etOrder);
return true;
}
return false;
}
/**
* Populate the order, like convert method
*
* #param mixed $result
*/
public function populate($result)
{
$orderData = $result->get_order_data();
// Standard post data
$this->id = $result->ID;
$this->order_date = $orderData['created_date'];
$this->modified_date = $orderData['created_date'];
$this->customer_message = '';
$this->customer_note = '';
$this->post_status = $orderData['status'];
// Billing email cam default to user if set
if (empty($this->billing_email) && !empty($this->customer_user)) {
$user = get_user_by('id', $this->customer_user);
$this->billing_email = $user->user_email;
}
$this->cancel_url = et_get_page_link('process-payment', array('paymentType' => $orderData['payment']));
$this->received_url = et_get_page_link('process-payment', array('paymentType' => $orderData['payment']));
}
public function get_shipping_address()
{
return "";
}
/**
* Get item of order
*
* #param string $type
* #return array
*/
public function get_items($type = '')
{
if (empty($type)) {
$type = array('line_item');
}
if (!is_array($type)) {
$type = array($type);
}
$type = array_map('esc_attr', $type);
$items = array();
if (in_array('line_item', $type)) {
$orderData = $this->etOrder->get_order_data();
if (isset($orderData["products"])) {
$index = 0;
foreach ($orderData["products"] as $id => $product) {
$items[$index]['name'] = $product['NAME'];
$items[$index]['product_id'] = $product['ID'];
$items[$index]['type'] = "line_item";
$items[$index]['qty'] = $product['QTY'];
$items[$index]['tax_class'] = '';
$items[$index]['line_subtotal'] = $product['AMT'];
$items[$index]['line_subtotal_tax'] = '0';
$items[$index]['item_meta'] = array();
$index++;
}
}
}
return $items;
}
/**
* Get total of order
* #author : Nguyễn Văn Được
* #return mixed
*/
public function get_total()
{
$orderData = $this->etOrder->get_order_data();
$total = $orderData["total"];
return $total;
}
/**
* Get order currency
* #author : Nguyễn Văn Được
* #return mixed
*/
public function get_order_currency()
{
$orderData = $this->etOrder->get_order_data();
return $orderData["currency"];
}
/**
* Get products from product item
* #author : Nguyễn Văn Được
*
* #param mixed $item
*
* #return bool|\ET_WC_Package
*/
public function get_product_from_item($item)
{
if (!empty($item['product_id'])) {
$_product = new ET_WC_Package($item['product_id']);
} else {
$_product = false;
}
return $_product;
}
public function get_checkout_order_received_url()
{
return $this->received_url;
}
public function set_checkout_order_received_url($received_url)
{
$this->received_url = $received_url;
}
public function get_cancel_order_url($redirect = '')
{
return $this->cancel_url;
}
public function set_cancel_order_url($cancel_url)
{
$this->cancel_url = $cancel_url;
}
/**
* Update order status
*
* #param string $new_status
* #param string $note
*/
public function update_status($new_status, $note = '', $manual = false)
{
if (!$this->id) {
return;
}
// Standardise status names.
$new_status = 'wc-' === substr($new_status, 0, 3) ? substr($new_status, 3) : $new_status;
$old_status = $this->get_status();
switch (strtoupper($new_status)) {
case 'COMPLETED':
case 'PUBLISH':
$this->post_status = 'publish';
break;
case 'PROCESSING' :
case 'ON-HOLD':
$this->post_status = 'pending';
break;
case 'CANCELLED' :
$this->post_status = 'draft';
break;
default:
$this->post_status = 'draft';
break;
}
$this->etOrder->post_status = $this->post_status;
$log = new WC_Logger();
$log->add('paypal', "Our Debug : " . $this->post_status);
wp_update_post(array('ID' => $this->etOrder->ID, 'post_status' => $this->post_status));
}
public function needs_shipping_address()
{
return false;
}
public function is_editable()
{
return parent::is_editable(); // TODO: Change the autogenerated stub
}
public function get_qty_refunded_for_item($item_id, $item_type = 'line_item')
{
$qty = 0;
return $qty;
}
public function get_total_refunded_for_item($item_id, $item_type = 'line_item')
{
$total = 0;
return $total * -1;
}
}
}
ET_WC_Package.php content:
<?php
if(class_exists("WooCommerce")) {
class ET_WC_Package extends WC_Product
{
protected $etPaynentPackage;
function __construct($product, $arg = array())
{
$this->product_type = 'pack';
parent::__construct($product);
}
public function get_sku()
{
return $this->post->ID;
}
public function is_virtual()
{
return true;
}
public function needs_shipping()
{
return false;
}
public function get_permalink() {
return get_permalink( $this->id );
}
}
}
PHP Strict Standards: Declaration of ET_WC_Order::get_total() should
be compatible with WC_Abstract_Order::get_total($context = 'view')
Change the get_total() function in ET_WC_Order.php to be
public function get_total($context = 'view')
{
$orderData = $this->etOrder->get_order_data();
$total = $orderData["total"];
return $total;
}
PHP Strict Standards: Declaration of ET_WC_Package::get_sku() should
be compatible with WC_Product::get_sku($context = 'view')
Change the get_sku() function in ET_WC_Package.php to be
public function get_sku($context = 'view')
{
return $this->post->ID;
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I try to learn how to make MVC model, but i have the following errors:
Notice: Sorry no method prepare has been found in ......./pdodatabasehandler.php 27
Fatal error: Call to a member function execute() on null in ..../abstractmodel.php 98
databasehandler.php
<?php
namespace BATRAHOSTMVC\Lib\Database;
/**
* Description of DatabaseHandler
*
* #author Mohamed Hassan Elmetwaly
* 25-03-2017
* mhe.developer#gmail.com
*/
abstract class DatabaseHandler {
const DATABASE_DRIVER_POD = 1;
const DATABASE_DRIVER_MYSQLI = 2;
private function __construct() {
}
abstract protected static function init();
abstract protected static function getInstance();
public static function factory()
{
// $driver = DATABASE_CONN_DRIVER;
// if($driver == self::DATABASE_DRIVER_POD)
// {
return PDODatabaseHandler::getInstance();
// } else if ($driver == self::DATABASE_DRIVER_MYSQLI)
// {
// return MySQLiDatabaseHandler::getInstance();
// }
}
}
pdodatabasehandler.php
<?php
namespace BATRAHOSTMVC\Lib\Database;
/**
* Description of pdodatabasehandler
* #author Mohamed Hassan Elmetwaly
* 25-03-2017
* mhe.developer#gmail.com
*/
class PDODatabaseHandler extends DatabaseHandler
{
private static $_instance;
private static $_handler;
private function __construct() {
self::init();
}
//public function __call($name, $arguments) {}
public function __call($name, $arguments) {
if(method_exists($this, $name))
{
$this->$name($arguments);
} else {
trigger_error('Sorry no method '. $name. ' has been found');
}
}
protected static function init(){
try{
self::$_handler = new \PDO(
'mysql:host='.DATABASE_HOST_NAME.';dbname='.DATABASE_DB_NAME,DATABASE_USER_NAME,
DATABASE_PASSW0RD);
//var_dump(self::$_handler);
//self::$_handler = new pdo("mysql:host=localhost; dbname=test", 'root', 'rootbootroot');
//return 'Connected';
} catch (\PDOException $e)
{
echo $e->getMessage( ) ." | ". $e->getCode( ) ;
}
}
public static function getInstance() {
if(self::$_instance === null){
self::$_instance = new self();
}
return self::$_instance;
}
}
abstractmodel.php
<?php
namespace BATRAHOSTMVC\Models;
use BATRAHOSTMVC\Lib\Database\DatabaseHandler;
//echo DATABASE_DB_NAME;
/**
* Description of abstractmodel
* #author Mohamed Hassn Elmetwaly (25-03-2017)
* mhe.developer#gmail.com
*/
class AbstractModel
{
const DATA_TYPE_BOOL = \PDO::PARAM_BOOL;
const DATA_TYPE_STR = \PDO::PARAM_STR;
const DATA_TYPE_INT = \PDO::PARAM_INT;
const DATA_TYPE_DECIMAL = 4;
const DATA_TYPE_DATE = 5;
/*
public static function viewTableSchema()
{
return static::$tableSchema;
}
*
*/
// we make path by reference
private function prepareValues(\PDOStatement &$stmt)
{
foreach (static::$tableSchema as $columnName => $type)
{
if($type == 4)
{
$sanitizedValue = filter_var($this->$columnName, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$stmt->bindValue(":{$columnName}", $sanitizedValue);
}
else
{
$stmt->bindValue(":{$columnName}", $this->$columnName, $type);
}
}
}
private static function buildNameParametersSQL()
{
$nameParams = '';
//$columnName (Column Name) => $type (Column datatype)
foreach (static::$tableSchema as $columnName => $type)
{
$nameParams .= $columnName. ' = :'.$columnName. ', ';
}
return trim($nameParams, ', ');
}
private static function create()
{
//global $connection;
$sql = 'INSERT INTO '. static::$tableName . ' SET '. self::buildNameParametersSQL();
$stmt = DatabaseHandler::factory()->prepare($sql);
$this->prepareValues($stmt);
return $stmt->execute(); // true of false
}
private static function update()
{
// global $connection;
$sql = 'UPDATE '. static::$tableName . ' SET '. self::buildNameParametersSQL(). ' WHERE '. static::$primaryKey .' = '.$this->{static::$primaryKey};
// $stmt = $connection->prepare($sql);
//$stmt = DatabaseHandler::factory()->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
$this->prepareValues($stmt);
return $stmt->execute(); // true of false
}
public function save()
{
return $this->{static::$primaryKey} === null ? $this->create() : $this->update();
}
public static function delete()
{
// global $connection;
$sql = 'DELETE FROM '. static::$tableName . ' WHERE '. static::$primaryKey .' = '.$this->{static::$primaryKey};
// $stmt = $connection->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
return $stmt->execute(); // true of false
}
public static function getAll()
{
// global $connection;
$sql = 'SELECT * FROM '. static::$tableName;
//$stmt = $connection->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
//return $connection->execute() === true ? $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, 'Employee', array('name', 'age', 'address', 'tax', 'salary')) : false;
//using fetchAll with this paramaters return values as OBJECT Of class which returned by get_called_calss() which called this method
$stmt->execute();
$result = $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, get_called_class(), array_keys(static::$tableSchema));
return is_array($result) && !empty($result) === true ? $result : false;
}
public static function getByPk($pk)
{
//global $connection;
$sql = 'SELECT * FROM '. static::$tableName. ' WHERE '. static::$primaryKey .' = '.$pk;
//$stmt = $connection->prepare($sql);
//$stmt = DatabaseHandler::factory()->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
//return $connection->execute() === true ? $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, 'Employee', array('name', 'age', 'address', 'tax', 'salary')) : false;
//using fetchAll with this paramaters return values as OBJECT Of class which returned by get_called_calss() which called this method
if($connection->execute() === true)
{
$obj = $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, get_called_class(), array_keys(static::$tableSchema));
return array_shift($obj);
}
return false;
}
public static function get($sql, $options = array())
{
/*
* example:
* $emps = Employee::get(
* 'SELECT name, age FROM employees WHERE age = :age',
* array(
* 'age' => array(Employee::DATA_TYPE_INT, 34)
* )
* )
* var_dump($emps)
*/
//global $connection;
//$stmt = $connection->prepare($sql);
$stmt = DatabaseHandler::factory()->prepare($sql);
if(!empty($options))
{
foreach ($options as $columnName => $type)
{
//$type[0] = datatype, $type[1] = columname
if($type[0] == 4)
{
$sanitizedValue = filter_var($type[1], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$stmt->bindValue(":{$columnName}", $sanitizedValue);
}
else
{
$stmt->bindValue(":{$columnName}", $type[1], $type[0]);
}
}
}
$stmt->execute();
$result = $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, get_called_class(), array_keys(static::$tableSchema));
return is_array($result) && !empty($result) === true ? $result : false;
/*
if(method_exists(get_called_class(), '__construct')){
$result = $stmt->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, get_called_class(), array_keys(static::$tableSchema));
//return is_array($result) && !empty($result) === true ? $result : false;
} else {
$result =$stmt->fetchAll(\PDO::FETCH_CLASS, get_called_class());
}
if((is_array($result) && !empty($result))){
$generator = function() use ($result){};
return $generator;
}
return false;
*/
}
}
employeecontroller.php
<?php
/**
* Description of abstractcontroller
*
* #author Mohamed Hassn Elmetwaly (25-03-2017)
* mhe.developer#gmail.com
*/
namespace BATRAHOSTMVC\Controllers;
use BATRAHOSTMVC\Models\EmployeeModel;
class EmployeeController extends AbstractController
{
public function defaultAction()
{
//EmployeeModel::getAll();
var_dump(EmployeeModel::getAll());
$this->_view();
}
}
employeemodel.php
<?php
namespace BATRAHOSTMVC\Models;
//use BATRAHOSTMVC\Models\AbstractModel;
//use BATRAHOSTMVC\Models\AbstractModel;
/**
* Description of employee
* #author Mohamed Hassn Elmetwaly (25-03-2017)
* mhe.developer#gmail.com
*/
class EmployeeModel extends AbstractModel
{
public $id;
public $name;
public $age;
public $address;
public $tax;
public $salary;
public static $db;
protected static $tableName = 'employees';
protected static $tableSchema = array(
'name' => self::DATA_TYPE_STR,
'age' => self::DATA_TYPE_INT,
'address' => self::DATA_TYPE_STR,
'tax' => self::DATA_TYPE_DECIMAL,
'salary' => self::DATA_TYPE_DECIMAL
);
protected static $primaryKey = 'id';
public function __construct($name, $age, $address, $tax, $salary) {
$this->name = $name;
$this->age = $age;
$this->address = $address;
$this->tax = $tax;
$this->salary = $salary;
}
public function __get($prop){
$this->$prop;
}
public function getTableName(){
return self::$tableName;
}
}
autoload.php
<?php
namespace BATRAHOSTMVC\LIB;
/*
* Applcation Constants
*/
/*
define('DS', DIRECTORY_SEPARATOR);
define('APP_PATH', dirname(realpath(__FILE__)).DS.'..');
define('PS', PATH_SEPARATOR);
define('CONTROLLER_PATH', APP_PATH.DS.'controllers');
define('MODEL_PATH', APP_PATH.DS.'models');
//echo CONTROLLER_PATH;
$path = get_include_path().PS.CONTROLLER_PATH.PS.MODEL_PATH;
set_include_path($path);
*/
class Autoload
{
public static function autoload($classname)
{
/* in Explanation */
$classname = str_replace('BATRAHOSTMVC', '',$classname);
$classname = str_replace('\\', '/', $classname);
$classname = $classname.'.php';
$classname = strtolower($classname);
if(file_exists(APP_PATH.$classname))
{
require_once APP_PATH.$classname;
}
/*
$class = str_replace('\\', '/', $classname);
$classFile = APP_PATH.DIRECTORY_SEPARATOR.strtolower($class).'.php';
if(file_exists($classFile))
{
require $classFile;
}
else
{
return;
}
*/
}
}
spl_autoload_register(__NAMESPACE__.'\Autoload::autoload');
frontcontroller.php
<?php
namespace BATRAHOSTMVC\LIB;
class FrontController
{
const NOT_FOUND_ACTION = 'notFoundAction';
const NOT_FOUND_CONTROLLER = 'BATRAHOSTMVC\Controllers\NotFoundController';
private $_controller = 'index';
private $_action = 'default';
private $_params = array();
public function __construct() {
$this->_parseUrl();
}
private function _parseUrl()
{
$url = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH),'/'), 3);
var_dump($url);
if(isset($url[0]) && $url[0] !='')
{
$this->_controller = $url[0];
}
if(isset($url[1]) && $url[1] !='')
{
$this->_action = $url[1];
}
if(isset($url[2]) && $url[2] !='')
{
$this->_params = explode('/', $url[2]);
}
// #list($this->_controller, $this->_action, $this->_params) = explode('/', trim($url, '/'),3);
// $this->_params = explode('/', $this->_params);
var_dump($this);
}
public function dispatch()
{
$controllerClassName = 'BATRAHOSTMVC\Controllers\\'.ucfirst($this->_controller).'Controller';
$actionName = $this->_action.'Action';
if(!class_exists($controllerClassName))
{
$controllerClassName = self::NOT_FOUND_CONTROLLER;
}
$controller = new $controllerClassName();
if(!method_exists($controller, $actionName))
{
$this->_action = $actionName = self::NOT_FOUND_ACTION;
}
$controller->setController($this->_controller);
$controller->setAction($this->_action);
$controller->setParams($this->_params);
$controller->$actionName();
}
}
I attached my files in the following link
http://www.mediafire.com/file/mdbxj5o3f6hd3gz/mvcyahia%285-4-2017%29.rar
Thanks in advance
public static function getInstance() {
if(self::$_instance === null){
self::$_instance = new self();
}
// here was the confusing the old value was return self::$_instance
return self::$_handler;
}
Your database / query object is null. So find how you call the database object so you can call its method.
Your code shows no prepare() method defined for your db class.
You are setting your PDODatabaseHandler::_handler property to the PDO, but when you are returning self(). Get it?
i have created a joomla component and when i click on publish and unpublish button in admin then i am getting such error.
Fatal error: Call to a member function publish() on boolean in ...\libraries\legacy\controller\admin.php on line 209
Please help
UPDATE
my View.html.php
require_once JPATH_COMPONENT . '/helpers/lab.php';
class labViewStructurelist extends JViewLegacy
{
protected $structurelist;
protected $pagination;
public $filterForm;
public $activeFilters;public $state;
public function display($tpl = null)
{
$this->structurelist = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
//print_r($this->pagination->pagesTotal);die();
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
$this->addToolBar();
$this->sidebar = JHtmlSidebar::render();
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
return parent::display($tpl);
}
protected function addToolBar() {
JToolBarHelper::title( JText::_('COM_LAB_LAB_DDDD'), 'generic.png' );
JToolBarHelper::publish('Structurelist.publish');
JToolBarHelper::unpublish('Structurelist.unpublish');
JToolBarHelper::deleteList('', 'patients.delete', 'JTOOLBAR_DELETE');
JToolBarHelper::preferences('com_lab');
}
}
Controller/stricturelist.php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controller library
jimport('joomla.application.component.controlleradmin');
class LabControllerStructurelist extends JControllerAdmin
{
public function getModel($name='Structurelist',$prefix='ssModel',$config=array('ignore_request'=>true))
{
$model=parent::getModel($name,$prefix,$config);
return $model;
}
}
models\structurelist.php
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
JFormHelper::loadFieldClass('list');
class LabModelStructurelist extends JModelList{
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'a.id',
'fullname', 'a.fullname',
);
$assoc = JLanguageAssociations::isEnabled();
if ($assoc)
{
$config['filter_fields'][] = 'association';
}
}
parent::__construct($config);
}
public function getListQuery()
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__ss_structure_tmp');
$search = $this->getState('filter.search');
$limit = $this->getState('filter.limit');
if (!empty($search)) {
$query->where('fullname LIKE "%' . $search .'%" ' );
}
if (!empty($limit)) {
$query->setLimit($limit);
}
return $query;
}
protected function populateState($ordering = 'a.fullname', $direction = 'asc')
{
$app = JFactory::getApplication();
if ($layout = $app->input->get('layout'))
{
$this->context .= '.' . $layout;
}
$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
$this->setState('filter.search', $search);
parent::populateState();
}
}
You need to provide the model to your controller using the getModel() method. Look in the articles controller of the com_content for example.
You need to add a table file with the publish function within:
defined('_JEXEC') or die;
use Joomla\Utilities\ArrayHelper;
class labTableStructurelist extends JTable
{
/**
* Constructor
*
* #param JDatabase &$db A database connector object
*/
public function __construct(&$db)
{
parent::__construct('#__ss_structure_tmp', 'id', $db);
}
/**
* Overloaded bind function to pre-process the params.
*
* #param array $array Named array
* #param mixed $ignore Optional array or list of parameters to ignore
*
* #return null|string null is operation was satisfactory, otherwise returns an error
*
* #see JTable:bind
* #since 1.5
*/
public function bind($array, $ignore = '')
{
$input = JFactory::getApplication()->input;
$task = $input->getString('task', '');
if (($task == 'save' || $task == 'apply') && (!JFactory::getUser()->authorise('core.edit.state', 'com_lab.structurelist.'.$array['id']) && $array['state'] == 1))
{
$array['state'] = 0;
}
if ($array['id'] == 0)
{
$array['created_by'] = JFactory::getUser()->id;
}
if (isset($array['params']) && is_array($array['params']))
{
$registry = new JRegistry;
$registry->loadArray($array['params']);
$array['params'] = (string) $registry;
}
if (isset($array['metadata']) && is_array($array['metadata']))
{
$registry = new JRegistry;
$registry->loadArray($array['metadata']);
$array['metadata'] = (string) $registry;
}
if (!JFactory::getUser()->authorise('core.admin', 'com_lab.structurelist.' . $array['id']))
{
$actions = JAccess::getActionsFromFile(
JPATH_ADMINISTRATOR . '/components/com_lab/access.xml',
"/access/section[#name='user']/"
);
$default_actions = JAccess::getAssetRules('com_lab.structurelist.' . $array['id'])->getData();
$array_jaccess = array();
foreach ($actions as $action)
{
$array_jaccess[$action->name] = $default_actions[$action->name];
}
$array['rules'] = $this->JAccessRulestoArray($array_jaccess);
}
// Bind the rules for ACL where supported.
if (isset($array['rules']) && is_array($array['rules']))
{
$this->setRules($array['rules']);
}
return parent::bind($array, $ignore);
}
/**
* This function convert an array of JAccessRule objects into an rules array.
*
* #param array $jaccessrules An array of JAccessRule objects.
*
* #return array
*/
private function JAccessRulestoArray($jaccessrules)
{
$rules = array();
foreach ($jaccessrules as $action => $jaccess)
{
$actions = array();
foreach ($jaccess->getData() as $group => $allow)
{
$actions[$group] = ((bool) $allow);
}
$rules[$action] = $actions;
}
return $rules;
}
/**
* Overloaded check function
*
* #return bool
*/
public function check()
{
// If there is an ordering column and this is a new row then get the next ordering value
if (property_exists($this, 'ordering') && $this->id == 0)
{
$this->ordering = self::getNextOrder();
}
return parent::check();
}
/**
* Method to set the publishing state for a row or list of rows in the database
* table. The method respects checked out rows by other users and will attempt
* to checkin rows that it can after adjustments are made.
*
* #param mixed $pks An optional array of primary key values to update. If not
* set the instance property value is used.
* #param integer $state The publishing state. eg. [0 = unpublished, 1 = published]
* #param integer $userId The user id of the user performing the operation.
*
* #return boolean True on success.
*
* #since 1.0.4
*
* #throws Exception
*/
public function publish($pks = null, $state = 1, $userId = 0)
{
// Initialise variables.
$k = $this->_tbl_key;
// Sanitize input.
ArrayHelper::toInteger($pks);
$userId = (int) $userId;
$state = (int) $state;
// If there are no primary keys set check to see if the instance key is set.
if (empty($pks))
{
if ($this->$k)
{
$pks = array($this->$k);
}
// Nothing to set publishing state on, return false.
else
{
throw new Exception(500, JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED'));
}
}
// Build the WHERE clause for the primary keys.
$where = $k . '=' . implode(' OR ' . $k . '=', $pks);
// Determine if there is checkin support for the table.
if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time'))
{
$checkin = '';
}
else
{
$checkin = ' AND (checked_out = 0 OR checked_out = ' . (int) $userId . ')';
}
// Update the publishing state for rows with the given primary keys.
$this->_db->setQuery(
'UPDATE `' . $this->_tbl . '`' .
' SET `state` = ' . (int) $state .
' WHERE (' . $where . ')' .
$checkin
);
$this->_db->execute();
// If checkin is supported and all rows were adjusted, check them in.
if ($checkin && (count($pks) == $this->_db->getAffectedRows()))
{
// Checkin each row.
foreach ($pks as $pk)
{
$this->checkin($pk);
}
}
// If the JTable instance value is in the list of primary keys that were set, set the instance.
if (in_array($this->$k, $pks))
{
$this->state = $state;
}
return true;
}
/**
* Define a namespaced asset name for inclusion in the #__assets table
*
* #return string The asset name
*
* #see JTable::_getAssetName
*/
protected function _getAssetName()
{
$k = $this->_tbl_key;
return 'com_lab.structurelist.' . (int) $this->$k;
}
/**
* Returns the parent asset's id. If you have a tree structure, retrieve the parent's id using the external key field
*
* #param JTable $table Table name
* #param integer $id Id
*
* #see JTable::_getAssetParentId
*
* #return mixed The id on success, false on failure.
*/
protected function _getAssetParentId(JTable $table = null, $id = null)
{
// We will retrieve the parent-asset from the Asset-table
$assetParent = JTable::getInstance('Asset');
// Default: if no asset-parent can be found we take the global asset
$assetParentId = $assetParent->getRootId();
// The item has the component as asset-parent
$assetParent->loadByName('com_lab');
// Return the found asset-parent-id
if ($assetParent->id)
{
$assetParentId = $assetParent->id;
}
return $assetParentId;
}
/**
* Delete a record by id
*
* #param mixed $pk Primary key value to delete. Optional
*
* #return bool
*/
public function delete($pk = null)
{
$this->load($pk);
$result = parent::delete($pk);
return $result;
}
}
Please note, that this is just an example of a table file, I can't guarantee that this would work just by copy&paste. Please check com_content/table for another example.
Also add a getTable() to your List single item model:
public function getTable($type = 'view_name', $prefix = 'labTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
Please check if file structure is correct:
List View
structurelist**s** -> list view with multiple items
|-> controller/structurelists.php
|-> models/structurelists.php
|-> view/structurelists/
Single View / List View (publish() for example)
structurelist -> single item view (edit view)
|-> models/structurelist.php (this is important for the publish() in the list view)
|-> models/forms/structurelist.xml
|-> tables/structurelist.php (this is important for the publish() in the list view)
|-> view/structurelist/
Feel free to comment if you need more help.
I've made a website in symfony. This website contains some forms with a checkbox choice and other fields.
The datas from the checkbox are serialized on flush.
It's all good.
Now i have to export this datas and i use the data exporter library from Sonata project. But the datas are still serialized and i have some things like that in my csv file:
a:2:{i:0;s:6:"Volets";i:1;s:22:"Panneau de remplissage";}
How can I unserialize my datas in order to have a clean csv file?
Here's my code
My controller
/**
* #Security("has_role('ROLE_WEBFORM')")
*/
public function exportAction(Request $request)
{
$filters = array();
$this->handleFilterForm($request, $filters);
if (!$filters['webform']) {
throw $this->createNotFoundException();
}
$webForm = $this->getRepository('CoreBundle:WebForm')->find($filters['webform']);
$source = new WebFormEntryIterator($webForm, $this->getEntityManager(), $this->get('ines_core.embedded_form.field_type_registry'), $filters);
return WebFormEntryExporter::createResponse('export.csv', $source);
}
and my class WebFormEntryExporter
class WebFormEntryExporter
{
public static function createResponse($filename, SourceIteratorInterface $source)
{
$writer = new CsvWriter('php://output', ';', '"', "", true, true);
$contentType = 'text/csv';
$callback = function() use ($source, $writer) {
$handler = \Exporter\Handler::create($source, $writer);
$handler->export();
};
return new StreamedResponse($callback, 200, [
'Content-Type' => $contentType,
'Content-Disposition' => sprintf('attachment; filename=%s', $filename)
]);
}
}
And my WebFormEntryIterator
class WebFormEntryIterator implements SourceIteratorInterface
{
protected $em;
protected $registry;
protected $repository;
protected $query;
protected $webForm;
protected $iterator;
public function __construct(WebForm $webForm, EntityManager $em, FieldTypeRegistry $registry, array $filters)
{
$this->webForm = $webForm;
$this->em = $em;
$this->registry = $registry;
$this->initQuery($filters);
}
/**
* {#inheritdoc}
*/
public function current()
{
$current = $this->iterator->current();
$entity = $current[0];
$data = [];
$data['ID'] = $entity->getId();
$data['Formulaire'] = $this->webForm->getName();
$data['Date de création'] = date_format($entity->getCreatedAt(), 'd/m/Y H:i:s');
foreach ($this->webForm->getEmbeddedFieldConfigs() as $fieldConfig) {
$header = $fieldConfig->getLabel();
$meta = $entity->getContentMeta($fieldConfig->getName());
$extension = $this->registry->get($meta->getFormat());
if (method_exists($extension, 'setEntityManager')) {
$extension->setEntityManager($this->em);
}
$value = $extension->formatMeta($meta);
$data[$header] = $value;
unset($extension);
}
$this->query->getEntityManager()->getUnitOfWork()->detach($current[0]);
unset($entity);
unset($webForm);
return $data;
}
/**
* {#inheritdoc}
*/
public function next()
{
$this->iterator->next();
}
/**
* {#inheritdoc}
*/
public function key()
{
return $this->iterator->key();
}
/**
* {#inheritdoc}
*/
public function valid()
{
return $this->iterator->valid();
}
/**
* {#inheritdoc}
*/
public function rewind()
{
if ($this->iterator) {
throw new InvalidMethodCallException('Cannot rewind a Doctrine\ORM\Query');
}
$this->iterator = $this->query->iterate();
$this->iterator->rewind();
}
protected function initQuery(array $filters)
{
$repository = $this->em->getRepository('InesCoreBundle:Content');
$qb = $repository->getWebFormEntryQueryBuilder();
$repository->applyWfeFilters($qb, $filters);
$this->query = $qb->getQuery();
}
}
Sorry for my broken English.
Thanks a lot
thanks chalasr.
I have to make the tratment in this file, in the current() function.
This is what I've done:
public function current()
{
$current = $this->iterator->current();
$entity = $current[0];
$data = [];
$data['ID'] = $entity->getId();
$data['Formulaire'] = $this->webForm->getName();
$data['Date de création'] = date_format($entity->getCreatedAt(), 'd/m/Y H:i:s');
foreach ($this->webForm->getEmbeddedFieldConfigs() as $fieldConfig) {
$header = $fieldConfig->getLabel();
$meta = $entity->getContentMeta($fieldConfig->getName());
$extension = $this->registry->get($meta->getFormat());
if (method_exists($extension, 'setEntityManager')) {
$extension->setEntityManager($this->em);
}
$value = $extension->formatMeta($meta);
if($this->is_serialized($value)) {
$value = unserialize($value);
$data[$header] = implode(' | ', $value);
} else {
$data[$header] = $value;
}
unset($extension);
}
$this->query->getEntityManager()->getUnitOfWork()->detach($current[0]);
unset($entity);
unset($webForm);
return $data;
}
public function is_serialized($data)
{
if (trim($data) == "") { return false; }
if (preg_match("/^(i|s|a|o|d){1}:{1}(.*)/si",$data)) { return true; }
return false;
}
I am creating a kind of shopping cart for a very specific purpose, and I have create two basic classes. The one class is made to describe a product in the cart, and the other class is the cart.
My CartItem class looks like that:
class CartItem
{
private $id = null; // This is the product id
private $qty = 0; // This is the product Quantity
private $price = 0; // This is the product price
private $name = ''; // This is the product name
private $options = array(); // This array contains the product options
private $rowid = null; // This is the product id in the cart
private $subtotal = 0; // This is the product sub total
public function __construct(
$id = null,
$qty = null,
$price = null,
$name = null,
$options = array()
)
{
$this->id = $id;
$this->qty = (float)$qty;
$this->price = (float)$price;
$this->name = $name;
$this->options = $options;
}
public function __get($name)
{
return $this->{$name};
}
...
public function setQty($qty = 0)
{
$this->qty = (float)$qty;
return $this->qty;
}
...
}
and my Cart class is the following:
class Cart
{
protected $cart_contents = array();
protected $cart = null;
protected function __construct()
{
$this->cart = new SessionContainer('cart_contents');
$this->cart_contents = $this->cart->offsetGet('contents');
if(count($this->cart_contents) <= 2)
{
$this->cart_contents = array(
'cart_total' => 0,
'total_items' => 0
);
}
}
public function insert(CartItem $item)
{
$save_cart = false;
if(($rowid = $this->_insert($item)))
{
$save_cart = true;
}
if($save_cart === true)
{
$this->_save_cart();
return isset($rowid) ? $rowid : true;
}
return false;
}
protected function _insert(CDOCartItem $item)
{
if($item->qty == 0)
{
return false;
}
if(is_array($item->options) && count($item->options) > 0)
{
$rowid = md5($item->id . serialize($item->options));
}
else
{
$rowid = md5($item->id);
}
$old_quantity = isset($this->cart_contents[$rowid]->qty) ? $this->cart_contents[$rowid]->qty : 0;
$item->setRowId($rowid);
$item->setQty($item->qty + $old_quantity);
$this->cart_contents[$rowid] = $item;
return $rowid;
}
public function update(CDOCartItem $item)
{
$save_cart = false;
if($this->_update($item) === true)
{
$save_cart = true;
}
if($save_cart === true)
{
$this->_save_cart();
return true;
}
return false;
}
protected function _update(CartItem $item)
{
echo "Is this empty : " . empty($item->qty) . " : " . $item->qty;
if(empty($item->qty) || empty($item->rowid) || !isset($this->cart_contents[$item->rowid]))
{
return false;
}
$item->setQty((float)$item->qty);
if($item->qty <= 0)
{
unset($this->cart_contents[$item->rowid]);
}
else
{
$this->cart_contents[$item->rowid]->qty = $item->qty;
}
return true;
}
}
Then I try to play with this structure:
$item = new CartItem('SKU-12321', 12, 47.82, 'Name');
$cart = Cart::Instance(); // I have apply the singleton patternt in my local files
$itemRID = $cart->insert($item);
$newItem = $cart->get_item($itemRID); // This method return the object based on ID and 100% works in my code
$newItem->setQty(25);
$cart->update($newItem);
But the problem is that I am getting the following result:
Is it empty : 1 : 25
The above line is printed in the Cart Class in the update method.
As you can see, I am testing if the $item->qty is empty, and the test returns true, and in the same value I am echoing the current item quanity that it is 25 so, the actual property it is not empty.
Am I doing something wrong ? In PHP Documentation they are describing that the function empty can be used to test for empty or null values in variables, but I am not sure if that works in properties.
Can somebody to help me please ?
I think the problem comes from your CartItem::__get(). I explain: $qty is private, so a empty($item->qty) returns true because it is not accessible outside the element, but when you access it with just $item->qty, the variable will be considered as unexisting (because it is private) so the __get() method will be called and will return the right value because you access it within the class.
I keep getting the following exception with a new resource Im making and i cant figure out why:
PHP Fatal error: Uncaught exception 'Zend_Application_Bootstrap_Exception' with message 'Circular resource dependency detected' in /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php:656
Stack trace:
#0 /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php(623): Zend_Application_Bootstrap_BootstrapAbstract->_executeResource('modules')
#1 /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php(580): Zend_Application_Bootstrap_BootstrapAbstract->_bootstrap('modules')
#2 /Library/WebServer/Documents/doctrine-dev/library/APP/Doctrine/Application/Resource/Doctrine.php(36): Zend_Application_Bootstrap_BootstrapAbstract->bootstrap('modules')
#3 /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php(708): APP_Doctrine_Application_Resource_Doctrine->__construct(Array)
#4 /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php(349): Zend_Application_Bootstrap_BootstrapAbstract->_loadPluginResource('doctrine', Array)
#5 /opt/local/lib/php/Zend/Application/Bootstrap/Bootstra in /opt/local/lib/php/Zend/Application/Bootstrap/BootstrapAbstract.php on line 656
As you'll see below ive created a Doctrine Resource that should load only in the general application bootstrap. In order to perform its tasks it needs the Modules resource to be bootstraped
so it calls $this->getBootstrap()->bootstrap('modules'). the Modules resoure never calls Doctrine though, and this seems to be where i get the circular dependency. Ive tried the code that is currently in the constructor for my Doctrine resource also as part of init directly and that doesnt seem to work either. An even bigger mystery to me though is that if i call $bootstrap->bootstrap('modules')
by itself before calling $bootstrap->bootstrap('doctrine') it all seems to play nicely. So why is there circular reference issue?
Relevant parts of application.xml
<resources>
<frontController>
<controllerDirectory><zf:const zf:name="APPLICATION_PATH" />/controllers</controllerDirectory>
<moduleDirectory><zf:const zf:name="APPLICATION_PATH" />/modules</moduleDirectory>
<moduleControllerDirectoryName value="controllers" />
</frontController>
<modules prefixModuleName="Mod" configFilename="module.xml">
<enabledModules>
<default />
<doctrinetest />
<cms>
<myOption value="Test Option Value" />
</cms>
<menu somevar="menu" />
<article somevar="article" />
</enabledModules>
</modules>
<doctrine>
<connections>
<default dsn="mysql://#####:######localhost/#####">
<attributes useNativeEnum="1" />
</default>
</connections>
<attributes>
<autoAccessorOverride value="1" />
<autoloadTableClasses value="1" />
<modelLoading value="MODEL_LOADING_PEAR" />
</attributes>
<directoryNames>
<sql value="data/sql" />
<fixtures value="data/fixtures" />
<migrations value="data/migrations" />
<yaml value="configs/schemas" />
<models value="models" />
</directoryNames>
</doctrine>
</resources>
Doctrine Resource
<?php
class APP_Doctrine_Application_Resource_Doctrine extends Zend_Application_Resource_ResourceAbstract
{
protected $_manager = null;
protected $_modules = array();
protected $_attributes = null;
protected $_connections = array();
protected $_defaultConnection = null;
protected $_directoryNames = null;
protected $_inflectors = array();
public function __construct($options = null)
{
parent::__construct($options);
$bootstrap = $this->getBootstrap();
$autoloader = $bootstrap->getApplication()->getAutoloader();
$autoloader->pushAutoloader(array('Doctrine_Core', 'autoload'), 'Doctrine');
spl_autoload_register(array('Doctrine_Core', 'modelsAutoload'));
$manager = $this->getManager();
$manager->setAttribute('bootstrap', $bootstrap);
// default module uses the application bootstrap unless overridden!
$modules = array('default' => $bootstrap);
if(!isset($options['useModules']) ||
(isset($options['useModules']) && (boolean) $options['useModules']))
{
$moduleBootstraps = $bootstrap->bootstrap('modules')->getResource('modules');
$modules = array_merge($modules, $moduleBootstraps->getArrayCopy());
}
$this->setModules($modules); // configure the modules
$this->_loadModels(); // load all the models for Doctrine
}
public function init()
{
return $this->getManager();
}
public function setConnections(array $connections)
{
$manager = $this->getManager();
foreach($connections as $name => $config)
{
if(isset($config['dsn']))
{
$conn = $manager->connection($config['dsn'], $name);
}
if(isset($config['attributes']) && isset($conn))
{
$this->setAttributes($config['attributes'], $conn);
}
}
return $this;
}
public function setAttributes(array $attributes, Doctrine_Configurable $object = null)
{
if($object === null)
{
$object = $this->getManager();
}
foreach($attributes as $name => $value)
{
$object->setAttribute(
$this->doctrineConstant($name, 'attr'),
$this->doctrineConstant($value)
);
}
return $this;
}
public function setModules(array $modules)
{
//$this->_modules = $modules;
foreach($modules as $name => $bootstrap)
{
$this->_modules[$name] = $this->_configureModuleOptions($bootstrap);
}
return $this;
}
public function setDirectoryNames(array $directoryNames)
{
$this->_directoryNames = $directoryNames;
return $this;
}
public function getDirectoryNames()
{
return $this->_directoryNames;
}
public function getDirectoryName($key)
{
if(isset($this->_directoryNames[$key]))
{
return $this->_directoryNames[$key];
}
return null;
}
public function getModuleOptions($module = null)
{
if($module === null)
{
return $this->_modules;
}
if(isset($this->_modules[$module]))
{
return $this->_modules[$module];
}
return null;
}
public function doctrineConstant($value, $prefix = '')
{
if($prefix !== '')
{
$prefix .= '_';
}
$const = $this->_getConstantInflector()->filter(array(
'prefix'=>$prefix,
'key' => $value
));
$const = constant($const);
return $const !== null ? $const : $value;
}
/**
* getManager
* #return Doctrine_Manager
*/
public function getManager()
{
if(!$this->_manager)
{
$this->_manager = Doctrine_Manager::getInstance();
}
return $this->_manager;
}
protected function _getConstantInflector()
{
if(!isset($this->_inflectors['constant']))
{
$callback = new Zend_Filter_Callback(array('callback'=>'ucfirst'));
$this->_inflectors['constant'] = new Zend_Filter_Inflector(
'Doctrine_Core::#prefix#key',
array(
':prefix' => array($callback, 'Word_CamelCaseToUnderscore', 'StringToUpper'),
':key' => array('Word_SeparatorToCamelCase', 'Word_CamelCaseToUnderscore', 'StringToUpper')
), null, '#');
}
return $this->_inflectors['constant'];
}
protected function _configureModuleOptions(Zend_Application_Bootstrap_BootstrapAbstract $bootstrap)
{
$coreBootstrapClass = get_class($this->getBootstrap());
if(get_class($bootstrap) === $coreBootstrapClass)
{
// handled differently
$resourceLoader = $bootstrap->bootstrap('DefaultAutoloader')->getResource('DefaultAutoloader');
$moduleName = $resourceLoader->getNamespace();
}
else
{
// handle a module bootstrap
$resourceLoader = $bootstrap->getResourceLoader();
$moduleName = $bootstrap->getModuleName();
}
$resourceTypes = $resourceLoader->getResourceTypes();
$modelResource = isset($resourceTypes['model'])
? $resourceTypes['model']
: array('path'=>'models', 'namespace'=>'Model');
$modulePath = $resourceLoader->getBasePath();
$classPrefix = $modelResource['namespace'];
$modelsPath = $modelResource['path'];
$doctrineOptions = array(
'generateBaseClasses'=>TRUE,
'generateTableClasses'=>TRUE,
'baseClassPrefix'=>'Base_',
'baseClassesDirectory'=> NULL,
'baseTableClassName'=>'Doctrine_Table',
'generateAccessors' => true,
'classPrefix'=>"{$classPrefix}_",
'classPrefixFiles'=>FALSE,
'pearStyle'=>TRUE,
'suffix'=>'.php',
'phpDocPackage'=> $moduleName,
'phpDocSubpackage'=>'Models',
);
$doctrineConfig = array(
'data_fixtures_path' => "$modulePath/{$this->getDirectoryName('fixtures')}",
'models_path' => "$modelsPath",
'migrations_path' => "$modulePath/{$this->getDirectoryName('migrations')}",
'yaml_schema_path' => "$modulePath/{$this->getDirectoryName('yaml')}",
'sql_path' => "$modulePath/{$this->getDirectoryName('sql')}",
'generate_models_options' => $doctrineOptions
);
return $doctrineConfig;
}
protected function _loadModels()
{
$moduleOptions = $this->getModuleOptions();
foreach($moduleOptions as $module => $options)
{
Doctrine_Core::loadModels(
$options['models_path'],
Doctrine_Core::MODEL_LOADING_PEAR,
$options['generate_models_options']['classPrefix']
);
}
return $this;
}
}
Modules Resource
<?php
class APP_Application_Resource_Modules extends Zend_Application_Resource_Modules
{
protected $_prefixModuleNames = false;
protected $_moduleNamePrefix = null;
protected $_defaultModulePrefix = 'Mod';
protected $_configFileName = 'module.xml';
protected $_enabledModules = null;
public function __construct($options = null)
{
if(isset($options['prefixModuleName']))
{
if(($prefix = APP_Toolkit::literalize($options['prefixModuleName']))
!== false)
{
$this->_prefixModuleNames = true;
$this->_moduleNamePrefix = is_string($prefix)
? $prefix
: $this->_defaultModulePrefix;
}
}
if(isset($options['configFileName']))
{
$this->_configFileName = $options['configFileName'];
}
parent::__construct($options);
}
protected function _mergeModuleConfigs(array $applicationConfig)
{
$cacheManager = $this->_getCacheManager();
if(isset($applicationConfig['resources']['modules']['enabledModules']))
{
$applicationModulesOptions = &$applicationConfig['resources']['modules'];
$enabledModules = &$applicationModulesOptions['enabledModules'];
$front = $this->getBootstrap()->getResource('frontcontroller');
foreach($enabledModules as $moduleName => $moduleOptions)
{
// cache testing
// note cache keys for modules are prefixed if prefix is enabled #see _formatModuleName
if(!$cacheManager->test('config', $this->_formatModuleName($moduleName)))
{
$configPath = $front->getModuleDirectory($moduleName).'/configs/'.$this->getConfigFilename();
if(file_exists($configPath))
{
if(strpos($configPath, ".xml") === false)
{
throw new Exception(__CLASS__." is only compatible with XML configuration files.");
}
$config = new Zend_Config_Xml($configPath);
$enabledModules[$moduleName] = array_merge((array) $moduleOptions, $config->toArray());
//$this->setOptions($options);
$cacheManager->save('config', $enabledModules[$moduleName], $this->_formatModuleName($moduleName));
}
}
else
{
$options = $cacheManager->load('config', $this->_formatModuleName($moduleName));
$enabledModules[$moduleName] = array_merge((array) $enabledModules[$moduleName], $options);
}
}
}
return $applicationConfig;
}
public function init()
{
/**
* #var Zend_Application_Bootstrap_BoostrapAbstract
*/
$bootstrap = $this->getBootstrap();
if(!$bootstrap->hasResource('frontController'))
{
$bootstrap->bootstrap('frontController');
}
$front = $bootstrap->getResource('frontController');
$applicationConfig = $this->_mergeModuleConfigs($bootstrap->getOptions());
$bootstrap->setOptions($applicationConfig);
parent::init();
return $this->_bootstraps;
}
/**
* Format a module name to the module class prefix
*
* #param string $name
* #return string
*/
protected function _formatModuleName($name)
{
$name = strtolower($name);
$name = str_replace(array('-', '.'), ' ', $name);
$name = ucwords($name);
$name = str_replace(' ', '', $name);
$options = $this->getOptions();
if($this->prefixEnabled())
{
$name = $this->getModuleNamePrefix().$name;
}
return $name;
}
protected function _getCacheManager()
{
$bootstrap = $this->getBootstrap();
if(!$bootstrap->hasResource('cacheManager'))
{
$bootstrap->bootstrap('cacheManager');
}
return $bootstrap->getResource('cacheManager');
}
public function prefixEnabled()
{
return $this->_prefixModuleNames;
}
public function getModuleNamePrefix()
{
return $this->_moduleNamePrefix;
}
public function getConfigFilename()
{
return $this->_configFileName;
}
public function setEnabledModules($modules)
{
$this->_enabledModules = (array) $modules;
}
public function getEnabledModules($controllerDirectories = null)
{
if($controllerDirectories instanceof Zend_Controller_Front)
{
$controllerDirectories = $controllerDirectories->getControllerDirectory();
}
if(is_array($controllerDirectories))
{
$options = $this->getOptions();
$enabledModules = isset($options['enabledModules'])
? (array) $options['enabledModules']
: array();
$this->_enabledModules = array_intersect_key($controllerDirectories, $enabledModules);
}
elseif(null !== $controllerDirectories)
{
throw new InvalidArgumentException('Argument must be an instance of
Zend_Controller_Front or an array mathing the format of the
return value of Zend_Controller_Front::getControllerDirectory().'
);
}
return $this->_enabledModules;
}
public function setPrefixModuleName($value)
{
$this->_prefixModuleNames = APP_Toolkit::literalize($value);
}
}
Module Bootstrap Base Class
<?php
class APP_Application_Module_Bootstrap extends Zend_Application_Module_Bootstrap
{
public function _initResourceLoader()
{
$loader = $this->getResourceLoader();
$loader->addResourceType('actionhelper', 'helpers', 'Action_Helper');
}
}
Maybe this section of the e-book "Survive the Deep End" might help you : 6.6. Step 5: Fixing ZFExt_Bootstrap -- it specifically speaks about the error you are getting.
(I won't quote as there is quite a couple of long paragraphs, but, hopefully, this'll help)