Zend Framework action helpers - php

I'm pretty much newbie in Zend Framework action helpers and I am trying to use them with no success (I read a bunch of posts about action helpers, including http://devzone.zend.com/article/3350 and found no solution in like 8 hours). I used Zend Tool to setup my project and the name of the helper is Action_Helper_Common. No matter what I do, I get following error "Fatal error: Class 'Action_Helper_Common' not found". Currently, I have things set up like this:
zf version: 1.11.3
helper name: Action_Helper_Common
helpers location:
/application/controllers/helpers/Common.php
In Bootstrap.php i have following function:
protected function _initActionHelpers() {
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . '/controllers/helpers', 'Action_Helper');
Zend_Controller_Action_HelperBroker::addHelper(
new Action_Helper_Common(null, $session)
);
}
I also tried this without success (it was defined in Bootstrap.php before _initActionHelpers):
protected function _initAutoloader() {
$moduleLoader = new Zend_Application_Module_Autoloader(array(
'namespace' => '',
'basePath' => APPLICATION_PATH . '/controllers/helpers'));
return $moduleLoader;
}
So what am I doing wrong?!?! PLZ help, I am desperate and about to give up :)

You got error because you haven't setup autoloader for Action_Helper_*
Resource autoloader
Helper broker uses plugin loader to load helpers based on paths and prefixes you specified to it. That is why ::getHelper() can find your helper

you dont need to do (so remove it)
Zend_Controller_Action_HelperBroker::addHelper(
new Action_Helper_Common(null, $session)
); ,
since you already did
Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . '/controllers/helpers', 'Action_Helper');
when you will do
$myhelper = $this->getHelper('Common');
in your controller zf will lookinto directory /controllers/helpers/ for class name Action_Helper_Common and create an instance for you and return it.

For some reason the following line didn't work for me as well:
Zend_Controller_Action_HelperBroker::addHelper( new Action_Helper_Common() );
I just keep getting a 'Class not found' error each time I'm creating a new helper object explicitly.
This is what works for me:
Zend_Controller_Action_HelperBroker::getHelper('Common');
In this case, new Action_Helper_Common object gets created and is registered with Helper Broker.
Not sure though if it works for you, since you have a parameterized constructor.

Related

Using FirePHP with Zend Framework 2

I'm trying to use FirePHP with Zend Framework 2, but there seems to be something missing. Here's the basic code I'm trying to run:
$writer = new Zend\Log\Writer\FirePhp();
$logger = new Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('FirePHP logging enabled');
The error I get is "FirePHP Class not found". I was initially puzzled because I do have a FirePhp class in my Zend/Log/Writer folder. But then I saw that the class constructor requires a FirePhp\FirePhpInterface object. So I checked the Zend/Log/Writer/FirePhp folder and there's a FirePhpBridge class in there that implements FirePhpInterface, but it also requires a FirePHP instance in the constructor. I don't have any FirePHP.php file in my Zend/Log/Writer/FirePhp folder. Am I supposed to get this from somewhere else?
Update
I now have managed to get FirePHP working, but I'm trying to figure out how to do it in a clean way so this works. The only way I've gotten it to work is putting it in the root directory of my project and doing the following:
include_once('FirePHP.php');
$writer = new Zend\Log\Writer\FirePhp(new Zend\Log\Writer\FirePhp\FirePhpBridge(FirePHP::getInstance(true)));
$logger = new Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('FirePHP logging enabled');
I assume that normally I should be able to create a writer like so:
$writer = new Zend\Log\Writer\FirePhp();
However, where this goes wrong I believe is in the getFirePhp() function of the Zend\Log\Writer\FirePhp class. The class does this:
if (!$this->firephp instanceof FirePhp\FirePhpInterface
&& !class_exists('FirePHP')
) {
// No FirePHP instance, and no way to create one
throw new Exception\RuntimeException('FirePHP Class not found');
}
// Remember: class names in strings are absolute; thus the class_exists
// here references the canonical name for the FirePHP class
if (!$this->firephp instanceof FirePhp\FirePhpInterface
&& class_exists('FirePHP')
) {
// FirePHPService is an alias for FirePHP; otherwise the class
// names would clash in this file on this line.
$this->setFirePhp(new FirePhp\FirePhpBridge(new FirePHPService()));
}
This is where I get lost as to how I'm supposed to set things up so that this class_exists('FirePHP') call finds the right class and new FirePHPService() also works properly.
First you should add this code to Module.php of your module
return array(
//...
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
);
and here content of autoload_classmap.php
<?php
return array(
'FirePHP' => realpath(APPLICATION_PATH . '/vendor/FirePHP').'/FirePHP.php',
);
FirePHP.php(renamed from FirePHP.class.php) downloaded from official site.
then you can write below code in any place of your module and it will work
use Zend\Log\Writer\FirePhp;
use Zend\Log\Logger;
$writer = new FirePhp();
$logger = new Logger();
$logger->addWriter($writer);
$logger->info("hi");
Am I supposed to get this from somewhere else?
Yes, you need to get FirePHP into your project and autoloading.
If you're using composer (and I recommend that you do), just add:
"firephp/firephp-core" : "dev-master"
(or similar) in your composer.json and update. If you're not using composer, you should grab the firephp libs, and let your autoloader know about them.

Joomla: Call helper function from within a model?

I'm starting off with both php and Joomla development, and finding it difficult working within Joomla to do some fairly simple stuff. Went through the Joomla MVC example and Lynda (and have built a few simple views so far).
I have a helper file/class/function that outputs all the userids that exist in the "completed" table so I can display a link for either a new record based on that user or edit an existing user's record.
I've already used a different function in this helper file successfully in a different part of the component ( Joomla: Write and call a helper function in a component ).
When I do the same thing in the model, I'm getting this: "Fatal error: Call to protected method JModel::_createFileName() from context 'JView' in C:\wamp\www\ilplocal\libraries\joomla\application\component\view.php on line 773". When I try it in the view, works fine - but I need the output in the model.
Code:
lookups.php
abstract class LookupHelper {
public function other_functions($vars){
...
}
public function completions_exist() {
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->SELECT(' #__completed.completed_userid as UserID');
$query->FROM (' #__completed');
$query->GROUPBY (' #__completed.completed_userid ');
$db->setQuery($query);
$result = $db->loadResultArray(0);
return $result;
}
}
In the model:
$completions_exist = Jview::loadHelper('lookups');
$completions_exist = LookupHelper::completions_exist();
This line is throwing the error: $completions_exist = Jview::loadHelper('lookups');
I've found some really vague references to something called JLoader::register to pull in helper functions but can't find any good documentation on that in Joomla except for everyone saying to just use that. SO I tried using it like so:
JLoader::register('LookupHelper', dirname( JPATH_COMPONENT_ADMINISTRATOR).DS.'helpers'.DS.'lookups.php');
$completions_exist = LookupHelper::completions_exist();
which throws this error: "Fatal error: Class 'LookupHelper' not found in C:\wamp\path\to\model\not\to\lookups.php. Tried manipulating the JLoader::register(everything here) and it doesn't effect the path of the error message.
Thoughts? Why does it work in a view and not in the model? How do I use the helper functions within a model?
Thanks!
#####EDIT
Thanks to #cppl looks like it's a path issue with the second bit of code. Also I read that the .DS. notation will be phased out in future versions - so the code that's working is:
JLoader::register('LookupHelper', JPATH_COMPONENT_ADMINISTRATOR.'/helpers/lookups.php');
$completions_exist = LookupHelper::completions_exist();
Lets break this down:
In Joomla! your components helper file should be in `/mycomponent/helpers/lookup.php'
JLoader:: is the Joomla! way to do it, but you could just as easily use PHP's require_once eg. require_once JPATH_COMPONENT_ADMINISTRATOR.'/helpers/myfunctions.php';
Is your path right? - you're providing dirname(JPATH_COMPONENT_ADMINISTRATOR).DS.'helpers'.DS.'lookups.php' but you've wrapped the path to your component in dirname which will the parent element of the path only. So JLoader is looking in /administrator/helpers/lookups.php.
JPATH_COMPONENT_ADMINISTRATOR is initialised as part of Joomla!'s renderComponent() call in it's JComponentHelper class if you apply dirname to it when it's not setup you will get back a dot (ie. current directory) so in the model you could would be passing ./helpers/lookups.php to the JLoader call.
You can call helper within model by following method:
JLoader::import('helpers.events', JPATH_COMPONENT);
this will include the file helpers/events.php from the component directory.
$_helper = new EventsHelper();
echo $_helper->getAnyInsideMethod();exit;

Zend framework Krixton_JsonRpc_Client and call method

I'm trying to figure out what is going on below:
public function serviceAction(){
$config = Zend_Registry::get('config');
$client = new Zend_Http_Client();
$client->setAuth($config['api']['username'],$config['api']['password']);
$service = new Krixton_JsonRpc_Client($config['api']['endpoint'], $client);
switch($this->_getParam('task'))
{
case 'test':
if(!this->getParam('newsletter_id')){
$this->_helper->json(array('sent'=>false,'error'=>'Newsletter ID is invalid, must be numeric'));
return;
}
$request = $service->call('newsletter.send', array($this->_getParam('newsletter_id'),false));
$this->_helper->json($request->result));
break;
}
}
What I'm trying to find out is how does
`Zend_Registry::get('config')`, $client->setAuth and $service->call`
works?
I understand _getParam('task') is a method to get get or post variables but not sure about the others. I had a look through some Zend documentations but if someone could help me out that would be appreciated!
Two things are happening there, the first one is Zend_Registry. get()allow you to get a value previously registered in the registry via Zend_Registry::set('key', $value). Usually, 'config' is your application configuration, which is the application.ini file.
basically, you would register config using this bootstrap method:
protected function _initConfig()
{
$config = new Zend_Config($this->getOptions());
Zend_Registry::set('config', $config);
return $config;
}
The second ones are nothing else than methods of Zend_Http_Client. setAuth()is used to set a basic HTTP authentification, and call()is an internal method of your object Krixton_JsonRpc_Client.
If you're trying to understand deep down how does these methods work, you should read the man first (especially Zend_registry and Zend_Http_Client pages) and then read carefully the source code.
Zend_Registry::get('config') ('config' is name of an array in this case) is recalling data that was saved to the registry, probably in the Bootstrap.php to make the information in the application.ini(configuration file) available everywhere.
The Bootstrap.php probably caontains something similar to:
protected function _initRegistry() {
//make application.ini configuration available in registry
$config = new Zend_Config($this->getOptions());
Zend_Registry::set('config', $config);
}
$client->setAuth is simply providing user credentials to Zend_Http_Client() HTTP LINK that were stored in the configuration file and accessed through the $config array.
$service->call I'm quite sure what this doing because I'm not familiar with the class (likely custom) being used. It looks like a request for a newsletter is being made based on 'id'.

Zend Framework Class Displaying Code

I have a Zend Framework application running on a local web server. I've run into an issue where it displays the code for certain classes. It looks like the autoloader isn't working. Whenever it tries to use a class that should have been autoloaded, it crashes saying it can't find the class, and prints the contents of the php file containing the class it was looking for.
Here's my autoloader
protected function _initAutoload()
{
echo "in autoload";
// Set up autoload.
$obj_loader = Zend_Loader_Autoloader::getInstance();
$obj_loader->setFallbackAutoloader(true);
$obj_loader->registerNamespace('Gutterbling_');
return $obj_loader;
}
The class that can't be found is Gutterbling_Acl. It doesn't say the file can't be found, just the class.
Warning : dirty quick answer.
A look in one of my Zend app and I've seen this line just before the return statement (and I don't have the call to setFallbackAutoloader) :
$obj_loader = new Zend_Application_Module_Autoloader(array(
'namespace' => '',
'basePath' => APPLICATION_PATH));
Add it and test.
Ok... Sorry to waste everyone's time. The problem was, the remote server has php short tags enabled. The local server does not. The files that aren't working start with
Again, sorry about that. Hopefully this helps someone with the same problem.

How to add autoload-function to CodeIgniter?

I would like to be able to use OOP and create new objects in my controllers in CodeIgniter. So I need to use an autoload-function:
function __autoload( $classname )
{
require_once("../records/$classname.php");
}
But how can I add that to CodeIgniter?
You can add your auto loader above to app/config/config.php. I've used a similar autoload function before in this location and it's worked quite neatly.
function __autoload($class)
{
if (strpos($class, 'CI_') !== 0)
{
#include_once(APPPATH . 'core/' . $class . EXT);
}
}
Courtesy of Phil Sturgeon. This way may be more portable. core would probably be records for you; but check your paths are correct regardless. This method also prevents any interference with loading CI_ libs (accidentally)
the User guide about Auto-loading Resources is pretty cleat about it.
To autoload resources, open the application/config/autoload.php file and add the item you want loaded to the autoload array. You'll find instructions in that file corresponding to each type of item.
I would suggest using hooks in order to add this function to your code.
Enable hooks in your config/config.php
$config['enable_hooks'] = TRUE;
In your application/config/hooks.php add new hook on the "pre_system" call, which happens in core/CodeIgniter.php before the whole system runs.
$hook['pre_system'] = array(
0 => array(
'function' => 'load_initial_functions',
'filename' => 'your_hooks.php',
'filepath' => 'hooks'
)
);
Then in the hooks folder create 2 files:
First: application/hooks/your_functions.php and place your __autoload function and all other functions that you want available at this point.
Second: application/hooks/your_hooks.php and place this code:
function load_initial_functions()
{
require_once(APPPATH.'hooks/your_functions.php');
}
This will make all of your functions defined in your_functions.php available everywhere in your code.

Categories