Pass parameters on redirection internally - php

I have an endpoint which is doing something (facade-endpoint), and then redirecting to another endpoint (endpoint) in the same application. What I'm trying to do here is I want to pass few parameters on redirection, but I don't want to allow others to pass them when they call the second endpoint directly.
For example:
public function facadeEndpoint(FacadeEndpointRequest $request)
{
$var1 = SomeClass::doSomething();
$var2 = SomeClass::doSomethingElse();
$request = Request::create('endpoint', 'GET');
return app()->handle($request); // I want to pass $var1 and $var2 here, so that they don't get recalculated once again after the redirection
}
public function endpoint(EndpointRequest $request)
{
$var1 = SomeClass::doSomething();
$var2 = SomeClass::doSomethingElse(); // If the request came from facade-endpoint, I want to use passed values instead of calling SomeClass functions again
// do something...
}
However as I mentioned, I don't want people to be able to pass $var1 or $var2 to the request directly - they should only be calculated in the application.
Is it possible?

Maybe you can add an additional parameter to signal that it came from facade endpoint.
$request = Request::create('endpoint', 'GET', ['internal' => true]);
Then when you receive request in your endpoint you can check whether it exists.
if ($request->has('internal')) {
// from facade endpoint
} else {
// called directly
}
The problem with this being a GET request is that parameters will be present in the url.

Related

Is using if else statement to load view based on parameters after controller and action part of url efficient or is there a better way of doing this

I can have the following urls
www.example.com/accounts/
www.example.com/accounts/signup
www.example.com/accounts/signup/validate
www.example.com/accounts/login
for each case, accounts becomes my controller, and index, signup, signup and login becomes my actions (or methods) respectively. I have to render different views based on what my actions are. Here is an example of what my code looks like
index
$url_segments = explode('/', $url);
$controller = !empty($url_segments[0]) ? $url_segments[0] : 'home';
array_shift($url_segments); // removes the controller name from array
$action = isset($url_segments[0]) && !empty($url_segments[0]) ? $url_segments[0] : 'index';
array_shift($url_segments); // removes the action name from array
$controller = ucfirst($controller);
$controller = new $controller($url_segments);
$controller->$action();
controller class
class Accounts{
private $url_segments;
public function __construct() {
$this->url_segments = $url_segments;
}
public function index() {
// index code here
}
public function login() {
// login code here
}
public function signup() {
if (!isset($this->url_segments[0])) {
// url entered was: example.com/signup
} else if (isset($this->url_segments[0]) && $this->url_segments[0] == 'validate') {
// url entered was: example.com/signup/validate
}
}
}
from how my code appeared above, it can be seen that as parameters keep adding after the controller and action part of the url I'll need to keep using conditional statements to run the proper code as in the case of /signup/ and signup/validate. Is this method of using conditional statement to load view based on parameters efficient or is there a better way of doing this.
I would recommend you to make use of a routing system like Symfony Routing. There you could add a new Route for every url and redirect them to your specific controller.
Example Route:
$routes = new RouteCollection();
$routes->add('/accounts_signup', route('POST', "/accounts/signup", 'App\Controller\AccountController:signup'));
return $routes;
This route would call the signup method in the AccountController calss when www.example.com/accounts/signup get called with a post request.
I recommend you to use something like this. Even if this might be a bit complicated for the beginning, after reading (and understanding) the docs this will safe you a lot of time and it will make your code more readable as well.

what should be the argument in facebook authentication function in laravel?

I have a function for Facebook authentication.
public function loginWithFacebook(Request $request){
// get data from request
$code = $request->get('code');
// get fb service
$fb = \OAuth::consumer('Facebook');
// check if code is valid
// if code is provided get user data and sign in
if ( ! is_null($code))
{
// This was a callback request from facebook, get the token
$token = $fb->requestAccessToken($code);
// Send a request with it
$result = json_decode($fb->request('/me?fields=name,email,gender,age_range'), true);
print_r($result1);
}
// if not ask for permission first
else
{
// get fb authorization
$url = $fb->getAuthorizationUri();
// return to facebook login url
return redirect((string)$url);
}
}
I want to call this function from another controller.
So I do this:
app('App\Http\Controllers\socialMedia')->loginWithFacebook(Request $request);
but it returns the error
syntax error, unexpected '$request' (T_VARIABLE)
How do I solve this?
public function loginWithFacebook(Request $request){
This is called type hinting. The method is declared in a way that it will only accept a first parameter that is an instance of Request.
app('App\Http\Controllers\socialMedia')->loginWithFacebook(Request $request);
That is a method call, and in those you just pass the parameter – to specify a type at this point makes no sense.
So the correct way to call the method should be
app('App\Http\Controllers\socialMedia')->loginWithFacebook($request);

`setCookie()` that Slim framework provides will not work if I use `exit()` after it

I need to use an ajax request to perform login. Here's the function that request goes to:
function loginAdmin() {
$app = \Slim\Slim::getInstance();
if (auth()) {
$app->setCookie('admin', TRUE);
exit(TRUE);
}
exit(NULL);
}
And I will process the ajax response to see if it's true. But the cookie wouldn't be set. If I remove exit(TRUE) the cookie can be set.
I've read the source code of Slim, the setCookie() function calls \Slim\Http\Cookies::setCookie(), which set the key and value into $data member. But I'm not sure when the cookies are sent.
But I still don't know how does exit function affect setCookie function.
You cannot send response using exit(). You should echo() the response in the route. For example something like:
function loginAdmin() {
$app = \Slim\Slim::getInstance();
if (auth()) {
$app->setCookie('admin', TRUE);
return 1;
}
return 0;
}
$app->get('/foo', function {
echo loginAdmin();
});
Above code is not a good way to do authentication, but it shows the point.

Passing posted values from one controller to another in symfony

I have two controllers. I find problem in passing posted values from one controller to another. Here is a quick view,
This is the function 1
public function setRole(request $request){
this->forward(Path,array(role=>$role));
this->redirect(path of second controller);
}
This is the function 2.
public function getRole(request $request){
$role = $request->get('role');//when printing this $role, I am able to get the value of $role.
$sql = "select * from table where id=$role"; // I cannot get the value in this qry ,also, i cannot pass the value to a twig file
return render...(filename,array('roleid'=>$role));
}
Problem is I could'n access the variable "roleid" in my twig file of second controller. Always it goes empty.
Is there anything i have missed here?
You have missed the Documentation :
public function indexAction($name) {
$response = $this->forward('AcmeHelloBundle:Hello:fancy', array(
'role' => $role
));
// ... further modify the response or return it directly.
// But do not redirect afterwards!
// Just return the response that the forwarded controller returns
return $response;
}
In case anyone else finds this from Googling. From Symfony 3.3 you can use the session interface to pass things from one controller to another.
As the documentation says: To retrieve the session, add the SessionInterface type-hint to your argument and Symfony will provide you with a session.
use Symfony\Component\HttpFoundation\Session\SessionInterface;
public function indexAction(SessionInterface $session)
{
// store an attribute for reuse during a later user request
$session->set('foo', 'bar');
// get the attribute set by another controller in another request
$foobar = $session->get('foobar');
// use a default value if the attribute doesn't exist
$filters = $session->get('filters', array());
}

Set and get global variable in php (ZendFramework)

I am using ZendFramework with PHP, and I want to set and get a variable as a global variable. I.E. I set it in the class of Zend Controller and access it any action in the class.
For example:
<?php
class SubscriptionController extends Zend_Controller_Action
{
private $EMAIL = false;
private $USERNAME = false;
First I am validating email addres with ajax call
public function checkusernameAction()
{
$email = //query to find email;
if($email){
$EMAIL = true;
}else{
$EMAIL = false;
}
}
then I want subscribe user on the basis of private variable again with ajax call
public function subscribeAction
{
if($EMAIL == true)
{
//some stuff
}
}
I am getting private var by $this->EMAIL, but not able to access it
You can use Zend_Registry to use the variable throughout application.
You can set a variable like this
Zend_Registry::set('email', $EMAIL);
and later can get it like this
$email= Zend_Registry::get('email');
Looks to me like you are making two distinct requests calling, respectively, checkusernameAction() and subscribeAction(). Since these are distinct requests, the email value you set in the controller during checkusernameAction() will be gone on the second request which calls subscribeAction(). It's the same controller class, but you are looking at two distinct instances, one in each request.
As I see it, you can either:
Pass the email address in each AJAX request, but this seems unlikely since you get the email address from the first call to checkusernameAction().
Save the email in the session during the first checkusernameAction() call and then pick it up during the second subscribeAction() call.
Extract the "get email from username" code into a separate class or method and then call it in both places. After all, you don't want to get bitten by a "race condition" in which the state of the system changes between the two AJAX requests (maybe the user's email changes via some other process or via another set of requests that occur after the first AJAX request containing the call to checkusernameAction().
You can also used a function for set and get a value.
// Setter function
public function setConsumerKey($key)
{
$this->_consumerKey = $key;
return $this;
}
// Getter function
public function getConsumerKey()
{
return $this->_consumerKey;
}

Categories