Warning/Notice/Strict with Phalcon - php

I'm using Phalcon 1.3.3 and PHP 5.4.
In my controller i have something like:
public function indexAction() {
$this->response->setContentType('application/json');
$data = json_encode(['some data']);
$this->response->setContent($data);
return $this->response->send();
}
If I put an "echo" in this action, I can't see it anywhere and i think this is realted to the fact that Phalcon use buffer output (It is possible to get Phalcon\Mvc\View rendered output in variable?)
But that's not really my problem, my problem is that if I have warnings/notice about missing variable, or undeclared constant or using deprecated methods, I can't see those on the rendered page.
I can see them in the logs but not the page itself which is a bit annoying when developing. In production obviously it's not a problem.
PS: I have "display_errors" and "display_startup_errors" set to 1 and if I put an exist before rendering the page I see all the warnings

I use this to return json:
$expireDate = new \DateTime();
$this->response->setHeader('Access-Control-Allow-Origin', '*');
$this->response->setContentType('application/json', 'UTF-8');
$this->response->setExpires($expireDate);
$this->response->setHeader('Cache-Control', 'private, max-age=0, must-revalidate');
$this->response->sendHeaders();
echo json_encode(array('response' => $response, 'error' => $this->api_error));
and in index.php
/**
* Handle the request
*/
$application = new \Phalcon\Mvc\Application($di);
//disable view service in general
$application->useImplicitView(false);
if you want to disable view rendering just for some places, you can use in controller:
$this->view->disable();
echo $data;

Related

print statement in symfony

I'm new with symfony and I'm looking for a a kind of "print statement". Before I was programming only with java so I could see and keep track of the code on my "console output" inside the IDE. Basically I was using print system out
What could be the equivalent to symfony. For example
$user = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneById($id);
Could I do something like this:
echo $user, inside the controller? and see the result somewhere
Or I should allways render the $user:
return $this->render('FOSUserBundle::edit.html.twig', array(
'user' => $user,
'form' => $form->createView()
));
then I could only see the result on the edit.html
Is that the only way? (using render)
Later on, I would like to use PHPUnit but at the moment I want to start from the basics
Thank you!
Yes, you can:
public function fAction(Request $request){
// ...
$user = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneById($id);
var_dump($user); exit;
// or ...
exit(\Doctrine\Common\Util\Debug::dump($user));
// or if you've installed VarDumper component (see below):
dump($user, $anotherUser, $request);
exit;
// ...
}
Try installing VarDumper component, and use its dump() function.
There are many ways to print a variable for debugging purposes in the middle of the script.
One of them is to use var_dump().
Following code will dump your variable and terminate the script.
var_dump($users);
die();

Laravel 5.1 Cookie Issue

I'm trying to set a cookie when I load a view:
$cookie = Cookie::make('mycookie', $myval, 43200);
$view = view('myview')->with($data);
return Response::make($view)->withCookie($cookie);
And read the cookie on a later request:
if (Cookie::has('mycookie')) {
//do something
}
The cookie never gets set... where am I going wrong?
This works to reliably set a cookie with Laravel:
use Illuminate\Http\Request;
use Illuminate\Contracts\Cookie\Factory;
class MyClass
{
public function handle(Request $request, Factory $cookie)
{
$cookie->queue($cookie->make('myCookie', $request->someVal, 129600));
return redirect('/myPage');
}
}
You can create cookie like following
$view = view('myview')->with($data);
$response = new Illuminate\Http\Response($view);
return $response->withCookie(cookie('name', 'value', $minutes));
Or you can queue the cookie like below, and it will be sent with next request,
Cookie::queue('name', 'value');
return response('Hello World');
Read More
A possible cause of your missing cookie problem could be that if you have a invalid Blade directive the page will display normally however any cookies set will not be persisted.
I encountered this problem as I had included #script in my blade template rather than #section('script')
I suspect the reason the cookies does get set is that the bad directive causes an error in the compiled php code that the view gets cached as and so the processing crashes before the cookie is transferred.

Zend_view->render() not rendering

I have a cron job that is running through some cases and if there is an error it should send an e-mail.
My code for creating the view to the e-mails looks like this (it's in my model class):
$layout = new Zend_Layout();
$view = $layout->getView();
$view->case = $case;
$view->forms = $forms;
echo "One\n";
$view->addScriptPath(APPLICATION_PATH .'/modules/case/views/scripts');
echo "Two\n";
$returnview = $view->render('index/print.phtml');
echo "Three (it never comes here)\n";
return $returnview;
It never comes to the Three (as it says) (it doesn't gives a error, it just looks like it exit() there).
Anyone know why it never gets there?
we are using Zend FrameWork 1.12
As you are able to just render a view with $view = new Zend_View(); and the rest of the code can use this :)
from docs they are setting the template like this enter link description here
$returnview->setTemplate(APPLICATION_PATH
.'/modules/case/views/scripts/index/print.phtml);
return $returnview;
I think you are are confused with zend version < 2.0
Make sure that your display_error setting is set properly to see the error message
since you are using zend f-1.12 you can simply use $this->render("view"); from controller
You can access the view object from any where using
$returnview = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');

Preventing error pages caching when using Zend_Cache_Backend_Static

We're currently running an app that caches pages to static html files using Zend_Cache_Backend_Static. This works really well, except that our cache is getting filled with hundreds of empty files and folders when incorrect urls are requested. Is there any way to prevent a page being cached if an Exception is being thrown? I was surprised to discover that this wasn't standard behaviour.
I've done a little digging and the ZF code that actually deals with saving out the static html pages is as follows in Zend_Cache_Frontend_Capture:
public function _flush($data) {
$id = array_pop($this->_idStack);
if ($id === null) {
Zend_Cache::throwException('use of _flush() without a start()');
}
if ($this->_extension) {
$this->save(serialize(array($data, $this->_extension)), $id, $this->_tags);
} else {
$this->save($data, $id, $this->_tags);
}
return $data;
}
This function is the output_callback for ob_start. I've tried getting hold of the response object to test for status but it doesn't seem to work inside _flush.
$response = Zend_Controller_Front::getInstance()->getResponse();
if($response->getStatus() == '200') {
// do the save as normal
}
else {
// do nothing
return false;
}
My only other thought was to test the length of $data, only caching if strlen($data) > 0 seems to work but it doesn't feel robust enough.
Update:
Unfortunately by the time we hit the ErrorController the static page has already been written to the cache, so disabling the cache at that point won't work. However it is possible to remove the page based on $_SERVER['REQUEST_URI'], which is what is used as an id when the page is first written. This line can be added to the start of errorAction in the ErrorController:
$this->_helper->cache->removePage($_SERVER['REQUEST_URI'], true);
It works nicely, but I'd prefer not to write the page in the first place!
From further experimentation the problem is not down to standard Zend Framework exceptions that cause 404s (ie. Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE, Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER, Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION) but to my custom exceptions. This is now really obvious now that I think about it, as Zend_Cache_Backend_Static needs to be initialised in the init method of an action controller. Any situation where there is no route, controller or action it won't ever be initialised anyway.
I'm throwing exceptions in existing actions where a user may be querying for a non-existent article. Therefore caching has been enabled in init and the page has been written by the time we hit postDispatch in a Front Controller Plugin (still not sure why this is the case it just is) so I can't cancel at that point. One solution then is to cancel the cache at the point of throwing the exception. The standard method of managing static page caching is using the Zend_Controller_Action_Helper_Cache action helper. I've extended this to add a cancel method like so:
<?php
class Zend_Controller_Action_Helper_PageCache extends Zend_Controller_Action_Helper_Cache {
public function cancel() {
$cache = $this->getCache(Zend_Cache_Manager::PAGECACHE);
$cache->setOption('caching', false);
$cache->getBackend('disable_caching', true);
}
}
My action controller now looks like this:
<?php
class IndexController extends Zend_Controller_Action {
private $_model;
public function init() {
$this->_model = new Model();
// using extended pageCache rather than $this->_helper->cache:
$this->_helper->pageCache(array('index'), array('indexaction'));
}
public function indexAction() {
$alias = $this->_request->getParam('article');
$article = $this->_model->getArticleByAlias($alias);
if(!$article) {
// new cancel method will disable caching
$this->_helper->pageCache->cancel();
throw new Zend_Controller_Action_Exception('Invalid article alias', 404);
}
$this->view->article = $article;
}
}
You should alter your .htaccess file RewriteRules to check for filesizes with option -s
This way if an error should occur when a page is being cached (thus producing a 0 byte file) it won't permanently be stored in the cache.
If you are using the standard ErrorController to handle 404, 500, and unhandled exceptions, and you can get a reference to your cache object from there, you could disable caching from the error handler.
In your error controller (or wherever you would like to cancel caching from), try:
$cache->setOption('caching', false);
When the save() metod of Zend_Cache_Core is called by Zend_Cache_Frontend_Capture::_flush(), it will see the caching option is set to false and it will not actually save the data to the cache and return true.

How to specify Content-type when using Recess framework with Smarty

I am currently using the PHP Recess framework with the Smarty templating engine. In my controller, I have code similar to:
/**
* !View Smarty
* !RespondsWith Smarty
* !Prefix Views: templates/, Routes: /
*/
class XHomeController extends Controller {
/** !Route GET */
function index()
{
$this->title = "Some title...";
}
}
and, in the corresponding Smarty view, I refer to {$title} as usual.
The view renders correctly in all browsers except Android browsers (on my 2.3 Nexus One, on a 3.2 tablet as well as in the Android emulator). I think that I've traced the problem to the fact that the Smarty view is being rendered and sent to the browsers without a Content-type.
Using http://web-sniffer.net/, I notice that Content-type in the Response is empty.
How can I specify the Content-type in Recess when using Smarty? I've tried adding header('Content-type: text/html') to the method in the controller but this does not work.
Any idea of what I'm doing wrong?
I would like to see the SmartyView code in recess/framework/views. That class should have a canRespondWith() method that will verify if a view can respond with a certain MIMEType. For example:
class XmlView extends AbstractView {
public function canRespondWith(Response $response) {
return 'xml' === $response->request->accepts->format();
}
}
If this returns true, then the XmlView will be used. In the AbstractView class, the sendHeaders() method will set the Content-Type:
protected function sendHeadersFor(Response $response) {
header('HTTP/1.1 ' . ResponseCodes::getMessageForCode($response->code));
$format = $response->request->accepts->format();
header('Content-Type: ' . MimeTypes::preferredMimeTypeFor($format));
/* ... */
}
Look in recess/http/MimeTypes.class.php to see how 'xml' will respond with the correct headers. You also need to look in your SmartyView to see what mimetype you are returning to see what header will be set.

Categories