Symfony 2 Controller Action no return Response - function

I have been some time without programing in Synfony and I have some doubts.
Is posible that and Action Controller return a variable (for example and integer) instead of a Response Object or Json Object.
What I need is call a function inside another function in a different Controller. If the 2 functions live in the same Controller it has no problem (like this):
class AController{
public function AAction(){
$var = $this->BAction(); //Do whatever I want with $var
return Response ("Hello");
}
public function BAction(){
return 34; //return an integer instead of a Response
}
}
THE PROBLEM IS when the BAction is in another Controller. If I use a forward, Symfony expect that BAction return a Response object or a Json array, but I only want to return a simple variale.
Is this posible?? Return a simple integer...
Thanks a lot!!

No a Action must return a Response Object. But if you have two controllers (that will say two different classes) then you could create a service.
app/config/config.yml
services:
app.my_ownservice:
class: AppBundle\Services\OwnService
arguments:
entityManager: "#doctrine.orm.entity_manager"
app/Services/OwnService.php
namespace AppBundle\Services;
use Doctrine\ORM\EntityManager;
class OwnService {
/**
*
* #var EntityManager
*/
private $em;
public function __constructor(EntityManager $entityManager)
{
$this->em = $entityManager;
}
public function doSomething(){
// you could use the entitymanager here
return 'Okay i will do something.';
}
}
And from each controller (or whatever) you can do:
$myOwnService = $this->get('app.my_ownservice');
$text = $myOwnService->doSomething();
// echo $text;

A controller should never use another controllers action. Thats not the problem that Controllers solve. Symfony business logic structure is SOA based. (https://en.wikipedia.org/wiki/Service-oriented_architecture) Therefore for custom business logic you should always use either:
Services: http://symfony.com/doc/current/book/service_container.html
Events: http://symfony.com/doc/current/components/event_dispatcher/introduction.html

Related

How to make every action in a zend (1.12) controller return JSON?

I have a controller that is purely for API use (no view or layout).
I want every action to return JSON format and have the Content-Type in the response be application/json.
I could achieve the header part by using the controller postDispatch() but couldn't find a way to do json_encode() from single place (I know I can do it from every action however I wanted it to be centralized).
I have even tried to use a plugin and there to manipulate the request body but for some reason that is not clear to me it is always empty.
Currently my solution is as follows:
public function init()
{
// no Layout
$this->_helper->layout()->disableLayout();
// no views
$this->_helper->viewRenderer->setNoRender(true);
}
public function indexAction()
{
$data = array("likes","to","sleep");
echo Zend_Json::encode($data);
}
public function postDispatch()
{
$this->getResponse()->setHeader('Content-Type', 'application/json');
}
Now, if i only managed to do the echo Zend_Json::encode in one single place...
You can use the ContextSwitch action helper
The JSON context sets the 'Content-Type' response header to 'application/json', and the view script suffix to 'json.phtml'. By default, however, no view script is required. It will simply serialize all view variables, and emit the JSON response immediately.
You will need to register it within the controller.
class FooController extends \Zend_Controller_Action
{
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('list', 'json')
->addActionContext('bar', 'json')
->initContext('json'); // json arg here means that we only allow json
}
}
You would then need to pass the format parameter in the url /module/foo/bar/format/json or as a query parameter ?format=json
You can create your own controller plugin.
In preDispatch turn off layout and view renderer and in postDispatch set content-type header in response.
Next option is to assing data to view.
public function indexAction() {
$data = array("likes","to","sleep");
$this->view->assign('data', $data);
}
and in view script call json view helper <?php echo $this->json($this->data); and do not use layout.

The _redirect() function in zend framework

I made a file in library/My/Utils/Utils.php. The content of the file is :
class My_Utils_Utils{
public function test(){
$this->_redirect('login');
}
}
This class is called from a layout; the problem is with the _redirect(); I get this error : The page isn't redirecting properly. My question is how call the _redirect() function from a class made by you in ZEND framework 1 .
Thanks in advance.
Use redirect() instead of _redirect(). Usage is:
$this->redirect(<action>, <controller>, <module>, <param>);
In your case $this->redirect('login'); should do the trick.
You can use the redirector action-helper, which you can get statically from the HelperBroker using:
// get the helper
$redirectHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
// call methods on the helper
$redirect->gotoUrl('/some/url');
It should be noted, however, that the layout is considered part of the view layer. Typically, any checks that result in a redirect should probably take place earlier in the request dispatch-cycle, typically in a controller or in a front-controller plugin.
The _redirect function is provided by the class Zend_Controller_Action. You can fix this in two ways :
Extend Zend_Controller_Action and use _redirect
class My_Utils_Utils extends Zend_Controller_Action {
public function test(){
$this->_redirect('login');
}
}
in layout:
$request = Zend_Controller_Front::getInstance()->getRequest();
$response = Zend_Controller_Front::getInstance()->getResponse()
$util = new My_Utils_Utils($request, $response); // The constructor for Zend_Controller_Action required request and response params.
$util->test();
Use gotoUrl() function Zend_Controller_Action_Helper_Redirector::gotoUrl()
$redirector = new Zend_Controller_Action_Helper_Redirector();
$redirector->gotoUrl('login');
//in layout :
$util = new My_Utils_Utils();
$util->test();

Global MySQL query in Codeigniter

In an attempt to try and narrow my query down, I'm still very new to Codeigniter framework...
I want to define global variables (eg. in autoloaded helpers) and use global mysql queries throughout my site - but I don't understand how to do the latter (global mysql queries).
I understand the concept of defining single variables in a helper... and I understand the concept of creating a single mysql query in a model, loading it in a controller and using it in a view file (with a foreach loop).
How (and where) do I create a mysql query that can be autoloaded (or whatever) and used anywhere on my site - without the need to load it in every controller?
this might help.. models would probably be your best bet. below i have given some insite on how to use controlelrs/models/libraries in general, i would put my mysql code into the appropriate model file. and call it via any controller
// Library/profiles.php
class My_library
{
protected $CI;
public function __construct()
{
$this->CI =& get_instance(); // Existing Code Igniter Instance
}
public function my_lib_method()
{
// Your Code Here
// can communicate back with CI by using $this->CI
// $this->CI->load->view(....);
// $this->CI->load->model(...);
// ETC
}
}
// models/my_model.php
class My_model extends CI_Model{
public function my_mdl_method(){
// Your Code Here
}
}
// controllers/my_controller.php
class My_controller extends CI_Controller
{
public function my_ctrl_method(){
$this->load->library('my_library');
$this->load->model('my_model');
// calling a library method
$this->my_library->my_lib_method();
// calling a model method
$this->my_model->my_mdl_method();
}
}

Set Header as 'application/json' to all actions in controller YII

I am creating a rest api using yii framework so the basic output format would be json....
I want all actions in a controller to have header content-type as 'application-json'.
I tried to put it in beforeFilter function in the controller but it didn't work.
Can any one help me out...
Create an init() function in the Controller class (protected/components/Controller.php). This will be called when any Controller/Action is called. Eg:
public function init(){
if ($this->id == 1){
// perform controller specific function
}
}
The $this->id returns the controller id. You must obviously replace the 1 in the code above with the relevant controller id for the controller you want the function to take place with

prestashop: Display method results in JSON

I'm going to develop a method inside my Prestashop module to fetch list of products and return the result as JSON. I have no problem to get list of products however I don't know to use which hooks and how to return JSON result instead of returning back to a Prestashop page.
The best way is to use a specific controller in your module. the result of the controller is available by an URL.
(Your controller class have to extend the "ModuleFrontController" class)
In your module controller, you should change the default constructor by:
public function __construct($response = array()) {
parent::__construct($response);
$this->display_header = false;
$this->display_header_javascript = false;
$this->display_footer = false;
}
And, in your "postProcess" method, simply echo the string you want, using this for example:
$json = json_encode( (array)$object );
Finally, in a template, you can generate a link to this controller using:
{$link->getModuleLink('mymodule', 'mycontrolleurname', [], true)}