I am using cakephp 2.10.24. I need to use the variable returned from the controller in a php file(not a view), so I used the dispatch function to make a Cakephp request. The data is displayed by itself and I'm not able to execute some code after the dispatch call.
I tried adding to the controller but it didn't work
$this->autoRender = false;
$this->layout = false;
$this->autoLayout = false;
the controller action:
$this->autoRender = false;
$this->layout = false;
$this->autoLayout = false;
$this->response->body(json_encode(array(
'key' => 0,
'message' => 'Invalid request.'
)));
$this->response->send();
$this->_stop();
php file:
<?php
echo ('i\'m test file <br />');
include 'app/webroot/index.php';
$request = new CakeRequest('/controller/action/param');
$response = new CakeResponse(array('type' => 'application/json'));
echo $results = $Dispatcher->dispatch(
$request ,
$response,
array('return' => 'vars')
);
//some codes not running
var_dump($response);
print_r(json_decode($response));
?>
Got the results but still auto printing the result on the screen.
test file:
$dispatcher = new Dispatcher();
$response = new CakeResponse();
$results = $dispatcher->dispatch(new CakeRequest('/Controlller/Action/params'),$response);
print_r("response: ".$response);
action in the controller:
$this->autoRender=false;
$this->autoLayout=false;
$this->response->body($result);
$this->response->send();
Related
Is there any sample/tutorial working with both Aura router and dispatcher? I found a sample code on the documentation page:
// dispatch the request to the route handler.
// (consider using https://github.com/auraphp/Aura.Dispatcher
// in place of the one callable below.)
$callable = $route->handler;
$response = $callable($request);
// emit the response
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
http_response_code($response->getStatusCode());
echo $response->getBody();
and I wanna know how can I integrate the Aura dispatcher with this sample code.
The second question is when we want to retrieve a GET request using Aura router, we use something like this:
// add a route to the map, and a handler for it
$map->get('blog.read', '/blog/{id}', function ($request) {
$id = (int) $request->getAttribute('id');
$response = new Zend\Diactoros\Response();
$response->getBody()->write("You asked for blog entry {$id}.");
return $response;
});
How about the POST method? I tried the following code, but it cannot retrieve the firstname in a similar way:
$map->post('profile', '/profile', function ($request) {
$firstname = $request->getAttribute('firstname');
$response = new Zend\Diactoros\Response();
$response->getBody()->write("first name is {$firstname}");
return $response;
});
The output is missing the $firstname value:
first name is
There are multiple ways you can use Aura.Dispatcher. The example provided below is one way.
$route = $matcher->match($request);
So once you match the request, there can be a route or null.
If there is a route, you can get the $route->handler;. This can be either a callable or string.
It is your implementation that tells how the Dispatcher can be invoked. From https://gist.github.com/harikt/8671136
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use Aura\Dispatcher\Dispatcher;
use Aura\Router\RouterContainer;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
class Blog
{
public function browse(ServerRequest $request)
{
$response = new Response();
$response->getBody()->write("Browse all posts!");
return $response;
}
public function read(ServerRequest $request, $id)
{
$id = (int) $request->getAttribute('id');
$response = new Response();
$response->getBody()->write("Read blog entry $id");
return $response;
}
public function edit(ServerRequest $request, $id)
{
$response = new Response();
$response->getBody()->write("Edit blog entry $id");
return $response;
}
}
$dispatcher = new Dispatcher;
$dispatcher->setObjectParam('controller');
$dispatcher->setMethodParam('action');
$dispatcher->setObject('blog', new Blog());
$routerContainer = new RouterContainer();
$map = $routerContainer->getMap();
// NB : You can use # sign as in Laravel. So blog#browse
$map->get('blog.browse', '/blog', 'blog::browse');
$map->get('blog.read', '/blog/{id}', 'blog::read');
$request = Zend\Diactoros\ServerRequestFactory::fromGlobals(
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$matcher = $routerContainer->getMatcher();
$route = $matcher->match($request);
if ($route) {
foreach ($route->attributes as $key => $val) {
$request = $request->withAttribute($key, $val);
}
// Take special attention, how I am using the handler.
// Do what you want with the handler
list($controller, $action) = explode('::', $route->handler);
$params = [
'controller' => $controller,
'action' => $action,
'request' => $request,
// This is not needed, just showing for demo purpose
'id' => $request->getAttribute('id'),
];
$response = $dispatcher($params);
// emit the response
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
http_response_code($response->getStatusCode());
echo $response->getBody();
} else {
echo "No route found";
}
I repeat this is not the only way. There are other better ways, read https://github.com/auraphp/Aura.Web_Kernel if you are really interested to learn more.
Regarding your question about getting value from POST. No there is no other way. The router is not handling the POST values. I think probably PSR-7 could have improved a bit in those areas :-) .
While trying to request data from en external API, I want to control how the response is being passed to my view or database. However what would be the correct way to write the code below, so instead of simply echoing the data onto the view I would like to store it inside an object that I can pass to my view or model in a more controlled way?
public function index()
{
$contents = $this->saveApiData();
return View::make('stats.index')->with('contents', $contents);
}
public function saveApiData()
{
$client = new Client(['base_uri' => 'https://owapi.net/api/v3/u/']);
$res = $client->request('GET', "data" . "/blob");
echo $res->getStatusCode();
echo $res->getBody();
}
Just put them together in an array and return it. You never echo data in a function to return them.
public function saveApiData()
{
$client = new Client(['base_uri' => 'https://owapi.net/api/v3/u/']);
$res = $client->request('GET', "data" . "/blob");
$contents = [
'status' => $res->getStatusCode(),
'body' => $res->getBody()
];
return $contents;
}
I am working on Joomla 3.6 and I am very new in joomla. I am fetching the data from an api and I want to pass that data to a view. How can I do that.
Controler: user.php
public function profile() {
$wskey = sdafsda;
$companycode = 'sdafsd';
$client = 1;
$cardno = 'sdafsd';
$pin = 'sdaf';
$wsdl = 'http://example/service.asmx?wsdl';
$getdata = array(
'WSKey' => $wskey,
'CompanyCode' => $companycode,
'CardNo' => $this->EncryptData($cardno),
'Client' => $client,
'PIN' => $this->EncryptData($pin),
);
$soapClient = new SoapClient($wsdl);
try {
$result = $soapClient->GetProfile($getdata);
} catch (Exception $e) {
return $e;
}
}
And view is created in com_users->views->cprofile.
I want to show this data in default.php of cprofile views and Want to know how can I call a view with data.
Sorry might not be clear.
Iḿ trying to make an rest application using Phalcon, i save some of the info
of the logged in user in an session but i don't get this to work, my code:
$this->session->set( Sessions::USERINFO, array (
'login' => true,
'type' => UserTypes::ADMIN,
'username' => $this->user->getUsername(),
'adminid' => $this->user->getAdminID(),
'fullname' => $this->user->getFullName(),
'avatar' => $this->user->getAvatar() )
);
return $this->session->get( Sessions::USERINFO );
When he returns the session it works but when i try to get the session in an other request it returns empty
return array("session" => $this->session->isStarted(),
"session Data" => $this->session->get(Sessions::USERINFO));
isStarted returns true
get returns null
Sessions::USERINFO
is an class with const values
const USERINFO = "userInfo";
Session var creation
$di->setShared( 'session', function () {
$session = new Session();
$session->start();
return $session;
} );
I am using this to save my session:
$obj = $this->request->getJsonRawBody();
$user = Users::findFirstByUsername($obj->username);
if($user) {
if($this->security->checkHash($obj->password, $user->password)) {
unset($user->password);
$this->session->set('auth', $user->toArray());
$response = $user->toArray();
}
else {
$response = array('msg' => 'failed');
}
}
else {
$response = array('error' => 'User not found');
}
$this->setPayload($response);
return $this->render();
And this to recieve information from my session
if($this->session->get('auth')['username']) {
$response = $this->session->get('auth');
}
else {
$response = array('msg' => 'noInfo');
}
$this->setPayload($response);
return $this->render();
This is how I start my session:
$di->set('session', function () {
$session = new SessionAdapter();
$session->start();
return $session;
});
It works just fine, you might want to try this.
I found the problem. Had to enable this in my frondend application:
RestangularProvider.setDefaultHttpFields({
withCredentials: true
});
The frontend was not sending the cookie with every request.
I want get the error in my form but actually the return is empty.
The data is received by the controller. When I send a valid form everything is OK.
Here is my code :
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
// This part is OK
}
else {
$val = array();
// I get errors :
$val['error'] = $form->getErrors();
echo json_encode($val);
$response = new Response;
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
I tried to add array('error_bubbling'=>true) in my form builder but the return don't show any fields has an error...
The function getErrorsAsString() returns the right result but I want it to return an array.
you can use JsonResponse
use Symfony\Component\HttpFoundation\JsonResponse;
$response = new JsonResponse();
$response->setData(array(
'data' => 123
));
return $response;