Cant get codeigniter hooks working - codeigniter

I have spent several hours now, trying to figure out why i can't get a simple hook working in codeigniter.
I have enabled hooks in config.
i tripplechecked spelling and case.
I wrote the code below in config/hooks.php:
$hook['pre_controller'] = array(
'class' => '',
'function' => 'set_previous_page',
'filename' => 'previous_page',
'filepath' => 'hooks'
);
And then my previous_page.php file which is located in hooks folder:
function set_previous_page()
{
echo "Hi!"; die;
}
Obviously the purpose is not to echo Hi! and then stop the script execution, but it's just to get it working. And i did try several hook points. But pre_controller i should be able to output hi and kill the script, and then have hi as the only output.
But when i load my pages, it just loads as normal.
I tried on purpose, to mess up the syntax in the hook array, and it did give me an error, and the rest of the page was not loaded. That just tells me that, at least it does recognize that i have turned hooks on.
But from here on i am just lost. Dont know what to do?
Do you have any ideas? I'll try and sleep on it now, and hope that some smart fella in here has the answer! Thankyou in advance!
EDIT: By the way, i am using MX (modular extensions), phil sturgeons template library and Ion auth. Dont really think they should have an impact.

Your code doesn't look like the code in the manual. Did you check it?
http://www.codeigniter.com/user_guide/general/hooks.html
I just tried it locally, and it works fine.
application/config/hooks.php:
$hook['pre_controller'] = array(
'class' => '',
'function' => 'Myfunction',
'filename' => 'Myclass.php',
'filepath' => 'hooks',
'params' => ''
);
application/hooks/Myclass.php:
<?php
function Myfunction(){
echo "wut wut";
die;
}
With this all set, I visit the page and get a wut wut.
You're missing the php extension in the filename, but that'd throw an unexpected end of input exception if everything else was working.

This maybe very late respond, just incase someone encounter this kind of issue same as me using CI 3.x. Just make sure you enable hooks in config/config.php file $config['enable_hooks'] = TRUE; before you put entry in the config/hooks.php

Related

How can I define a constant that includes a space in my .env file?

New to Laravel (love it though), so I apologize in advance. I am coming from CodeIgniter land, so it's quite possible I'm trying to bring over some bad habits.
I am defining a constant in my .env file to keep all of my email & names in one spot. In this case, I am storing my general email information:
.env
NOREPLY_EMAIL=noreply#mysite.com
CONTACT_EMAIL=contact#mysite.com
CONTACT_NAME=Bill Brasky
Then in my controller, I am accessing this like this:
MyController.php
Mail::send('emails.template', array('key' => 'value'), function ($message) {
$message->from(env('NOREPLY_EMAIL'), 'My Site');
$message->to(env('CONTACT_EMAIL'), env('CONTACT_NAME'))->subject('My Subject');
});
Everything works great until I put the CONTACT_NAME in my .env file. I get this error:
Uncaught exception 'ReflectionException' with message 'Class log does not exist'
I remove the CONTACT_NAME constant and all is well again. Any suggestions on what I am doing wrong would be greatly appreciated!
Wrap the value in quotes
CONTACT_NAME="Bill Brasky"

How to increase CakePHP Debugger maximum depth

I'm trying to debug my program by logging information from an ajax call. This is something that doesn't render a view, just runs asynchronously. The log will only display arrays to a depth of 3, and the documentation doesn't seem to have any notion that someone might want more information than that.
Please, how do I increase this depth so I can have access to this information without finding weird ways to render my ajax call? Or, if doing this isn't the "Cake" way, is there a better way to output info to a log or console for debugging?
I think this is not the case of CakePHP but an issue with XDebug or PHP configuration itself. You can try to add this line to your php.ini
xdebug.var_display_max_depth = 5
It works if you debug with var_dump(). You should write how do you try to debug, bacause different methods depends on different mechanisms.
If it doesn't work you can try to make the Cake to display original PHP error messages instead of its own error handler messages. In your core.php find code like this:
Configure::write('Error', array(
'handler' => 'displayErrorWithoutCrap',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
And change it into this:
Configure::write('Error', array(
//'handler' => 'ErrorHandler::handleError',
'handler' => 'displayErrorWithoutCrap',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
and add this line at the end of bootstrap.php :
function displayErrorWithoutCrap() {
return false;
}
I ended up submitting a ticket to the Git project for CakePHP and it was confirmed that the debug depth for arrays is hard-coded for log files. The response indicated that it would be considered for a change in the next version.
I ended up finding the number in the Debug class and changed it to a larger number which gave me more depth. Not the best fix, but it works for now until support is added to the next version.

Codeception API testing: stuck at passing json payload to REST service

I found this cool tool called codeception for testing in PHP. I am liking it a lot. I started writing API test cases. But I am stuck at POSTING json payload to a REST service. How can I perform this?
I have a REST end point called /order, which accepts a JSON payload. The service is build on Laravel4, so I accept the payload in Laravel4 using Input::json()->all().
I have tried something like this
$filename = __DIR__.'/createOrder.json';
$I->haveHttpHeader('Content-Type', 'application/json');
**$I->sendPOST('order', null, array($filename));**
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
But it gives me 500 internal server error, as my service accepts json payload and not in the form of file.
Anyone has worked on something like this before?
Thanks in advance.
I know this is an old question but for others who stumble on this, try:
$I->haveHttpHeader('Content-Type','application/json');
it definitely should work.
I got it working by doing this
$exampleData = [
'name' => 'adam',
'age' => 99
];
$json = json_encode($exampleData);
$I->sendPOST('/endpoint', $json);
For more details see this Github issues
# Sameer, I have tried and faced similar issue. I then went with a work around for this.
$filename = __DIR__.'/createOrder.json';
$I->sendPOST('order', getPostParams($filename));
Now create a new folder called "helpers" inside your suite and add "<suiteName>Helper.php" to it.
Add the following code there
function getPostParams($filename){
if(!file_exists($filename)){
print "MISSING FILE ".$filename."\n";
return;
}
$jsonData= json_decode(file_get_contents($filename));
if(!$jsonData){
print "INVALID JSON CONTENT ".$filename."\n";
return;
}
return (array)($jsonData);
}
Go to _bootstrap.php inside "tests" folder and add this
require_once('<suiteName>/helpers/<suiteName>Helper.php');
Now do a build and run the test suite. you should be able to get pass the error :)

How to use translations in Yii console application?

I have created a console Yii application that works as a background worker for a web app - it sends out emails and it needs to send them with translated messages.
For some reason however, the messages are not translated when using Yii::t
If I set the language to something else than english with Yii::app->setLanguage('et_ee'), and check that it is really changed with Yii::app->getLanguage() the texts are always in english.
When I run this same command from web, the texts are correctly translated.
I guess there must be something special I have to do for the translatiosn to work in a console application?
I have this error to. I dont know how is fix it. I am get lang array trow require('path/to/message/ru/message.php') in to var and use it. It is wrong, but it is work for me.
You need to specify the messages component in your console.php configuration
'messages' => array(
'class' => 'CDbMessageSource',
'forceTranslation'=>true,
'sourceMessageTable' => 'source_message',
'translatedMessageTable' => 'translated_message',
),
Just add string (For example - russian languages):
'language' => 'ru'
in config/console.php.

Get environment inside controller

I have a situation in one of my controllers that should only be accessed via AJAX, I have the following code.
if (!$request->isXmlHttpRequest()) {
$response = new Response();
$response->setContent('AJAX requests only!');
return $response;
}
When I am testing this gives me an issue because the request hasn't actually been made via AJAX. This then breaks my tests every time. How should I go about working around this?
My Ideas:
I have tried to set a server header but have had absolutely no success.
Check if I am in the test environment in the controller and don't do the check if it is. I know this is dirty, but it would work. :-/ The problem was that I couldn't figure out how to discover what environment I am in.
Anyone else have any other ideas or tips that I am missing to get one of the above to work?
Of course in Icode4food's case, it's better to use Matt's solution, but here is how to find the current environment:
$this->container->getParameter(‘kernel.environment’)
Looking at the code for isXmlHttpRequest in class Request and method getHeaders in class ServerBag, the piece of code below should do the trick:
$client->request(
'GET',
'/path/to/test',
array(),
array(),
array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
)
);
I did not test it personally but I think it should works. The line of code below in Request is used to check if the http request is a XmlHttpRequest.
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
In the code, $this->headers is set using:
$this->headers = new HeaderBag($this->server->getHeaders());
The method getHeaders creates an array of headers. Each server variable starting with HTTP_, plus some special server variables like CONTENT_TYPE, are put in this array.
Hope this helps.
Regards,
Matt

Resources