print statement in symfony - php

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();

Related

How to print out value on controller Laravel?

I'm beginner on Laravel...
How to debug some value on controller in Laravel, result can show to console like syntax console.log() on javascript?
example controller function :
class TestMeController extends Controller {
public function __construct()
{
$this->middleware('jsonify');
}
public function callMe($id)
{
$params = Request::all();
console.log($id); <== how to write code on Laravel?
}
}
In Laravel use dd($id) or if you don't want to halt the execution, you can use dump($var).
You can still always use PHP's native functions like var_dump, die and print_r.
You can Use these several methods for printing in Laravel.
1. dump($var)
2. dd($id)
3. var_dump($var)
4. die($var)
5. print_r($var)
dd($var) is great because it stops the program after it runs so by moving it around you get a good sense of which line of code is causing an error.
In my case I am using laravel 7 with blade templates and to test my controller
(MVC ARCHITECHTURE)
I usually use:
return dd($variable)
or even just
return $variable
If you just want to see the data
$events = new Event();
echo "<pre>";
print_r($events->all()->toArray());
echo "</pre>";
die;
Use a return response with json:
return response()->json($dataVar, status_code);
instead console.log();
return response()->json($id, 200);

Warning/Notice/Strict with Phalcon

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;

how to fix CConsoleApplication.user undefined in a command class in yii framework?

I am having that error , whenever I ran my simple cron script in shell ,
any idea how to fix that thing ?, from the error itself, it says the .user is undefiend,
when I placed the
'user' => array(
// enable cookie-based authentication
'allowAutoLogin' => true,
'loginUrl' => array('myaccount/blah/login'),
in the console config, it is looking for a "Class" ,, what class am i supposed to include in that array? , this user login url is using an LDAP stuff in loggin in and authentication, what should I do ?
A CConsoleApplication is for handling offline tasks. For example, the application starts a cronjob within a linux system. The application checks each day if a registered user of your website should change his password, because it must be changed every 3 month. If the password expired send an email.
To preselecting the users you have set a scope condition to check the status of a user, as well as a scope to restricted signed in users on her own data:
public function scopes(){
return array(...,
'user' => array(
'condition'=>'id='.Yii::app()->user->id,
),
'active' => array(
'condition'=>'status='.self::STATUS_ACTIVE,
), ...
);
}
Now, in your CCA-Code you use the active scope to get all users:
$usersArray = User::model()->active()->findAll(); ...foreach.... The Problem here is in the use of the extended class, the CActiveRecord-class. Mostly used as a class extension in models, which are stored in a database. In this CActiveRecord-class the CActiveRecord->__call function is used to get all stored scopes of a model. After that the class merged the actually requested scopes with the rest of the database criteria. The fact that all scopes are loaded first occures the error in loading the user-scope, include Yii::app()->user->id. The WebUser is called and throws the exception 'CException' with message 'attribute "CConsoleApplication.user is not defined'. You wouldn't call the WebUser, but the automatism arrange this for you :-)
So, do it like schmunk says. Generate in your scope code an exception part where ensures that Yii::app()->user is not called:
public function scopes(){
if (Yii::app() instanceof CConsoleApplication) {
$user = array(''); //no condition
}else{
$user = array(
'condition'=>'id='.Yii::app()->user->id,
);
}
return array(
'user' => $user,
'active' => array(
'condition'=>'status='.self::STATUS_ACTIVE,
), ...
);
}
I hope the explanation helps and perhaps also for other problems.
Short answer: You can't use CWebUser in console application. Don't include it in your config/console.php
Long(er) answer: If you rely on a component, which needs CWebUser, you'll have to detect this in the component and create some kind of workaround for this case. Have a look at this code piece for an example how to detect, if you're running a console app.
Try this
public static $console_user_id;
public function init() {
if (Yii::app() instanceof CConsoleApplication) {
if (self::$console_user_id) $this->id = self::$console_user_id;
return false;
}
parent::init();
}
solved my problem by using update, instead of save in the script...no need to use user array and CWebUser class
I had the same problem. Screened all answers given here and found some good point, but solved my problem my way, although it may not be the best.
First off all I had to figure out that my Cron Jon threw the aforementioned Exception because inside the Cron job I was running a script which had this part of code in it
if(Yii::app()->user->isAdmin()) {...} else {...}
So the console threw the error since the user was not defined. I changed my code in such a way that I tested if the console was running it. The changed code is as follows:
$console = false;
try {
$test = Yii::app()->user->isAdmin();
}
catch (CException $e) {
$console = true;
}
if($console || (!$console && Yii::app()->user->isAdmin()) {...} else {...}
As said, not perfect, but maybe a solution for someone.

Unit testing Zend_Session

i have problem with testing zend_session, my test look like that:
Bootstrap.php
public function _initSession() {
try
{
Zend_Session::setSaveHandler(new APP_Session_SaveHandler_Memcached());
Zend_Session::start();
$session = new Zend_Session_Namespace('APP');
Zend_Registry::set('session', $session);
}
catch(Exception $e)
{
Zend_Registry::get('log')->err($e);
}
}
SessionTest.php
public function testSession() {
$session = Zend_Registry::get('session');
$session->setExpirationSeconds(1);
$session->testIndex = "testValue";
$this->assertEquals('testValue', $session->testIndex);
sleep(3);
$this->assertEquals(null, $session->testIndex);
}
first assertion is ok, but the second always say that value of $session->testIndex is "testValue", when it should be null right?
If i'am wrong, please tell me, because I can't figure it out.
The expiry time isn't evaluated every time you access data from the session class, just when it is first loaded. A typical PHP script should never take over a second to execute, so the case you are trying to test shouldn't ever happen in a real world situation.
I'd also add that there's not a lot of point testing functionality that exists in ZF like this - the ZF classes are already unit tested. Test your application, not the framework.

Trying to debug a symfony app showing the list of all the functions called, debug_backtrace() doesn't fits me

im trying to debug a symfony app.
I've added a debug_backtrace() calling to this function below. It
outputs a list of functions called, but the save() function (that is
just before the debug_backtrace() calling) is not that list.. why? any other way to debug that shows more things, in this case the save() calling ?
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()));
if ($form->isValid())
{
$sf_guard_user = $form->save();
var_dump(debug_backtrace());
die("fsdgsgsdf");
$this->redirect('guardausuario/edit?id='.$sf_guard_user-
>getId());
}
}
Regards
Javi
I've just got my target using
xdebug_start_trace('/tmp/foo');
$usuario = $form->save();
xdebug_stop_trace();
http://www.xdebug.org/docs/all_functions
Javi
Symfony's web developer bar has some great information.
What exactly are you trying to see? Somethings it is good to echo $form because it will reveal all of the fields and any hidden fields in the form. Also, remember to include [_csrf_token] in your View if you are writing a custom View.
And... Symfony and xDebug are a good combination.
In php.net (http://php.net/manual/es/function.debug-print-backtrace.php) bishop exposes this solution:
$e = new Exception();
$e->getTraceAsString();
It gives a short but concise response for all the functions being called. It perfectly suited my needs, so I can log what happened without being lost.

Categories