SlimFramework - Access Route Variables Via Custom Function - php

I have the following route I'm setting.
$app->post(
'/:device/admin/(/)',
'get_user',
$validate_user(
array(
'Admin',
'Manager'
),'
templates'
),'
render_bronzeservice'
)->conditions(
array('device'=>'(tablet|desktop|mobile)')
);
I want to be able to pass the route variable :device to the function $validate_user
How do I do this?
For the function render_bronzeservice, it simply expects a parameter for the device, but this does not work for custom functions or I can't figure it out.
Any help is appreciated!

Ok well I found a workaround for now, its ugly but it will work. Since I get the user data in the function before it, I do the check there for the parameter.
Oddly for some reason it does not send it as a string? But sends it as a route object to the first function.
So my get_user function looks like this.
function get_user($route){
global $user;
global $device;
//If there is any route device info...
if(isset($route->getParams()['device'])){
$device = $route->getParams()['device'];//set the device sent from the route.
}
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
//Do database lookup on userID and set to global $user
//echo "User Found";
$user = User::find(array('id' => $_SESSION['userid']));//sets the user super global variable from the database accordingly.
}else{
//echo "User Not Found<br/>";
}
}
By using a global variable to keep track of the device, I can then read it in the next function in line $validate_user by declaring global in that function.
It's a weird workaround, but working for now.

Related

How can i access a variable outside that function in codeigniter

I am sorry for asking this basic level question. I have fetched some data from DataBase and stored it to a variable inside a function, and wanted to get the value of that variable outside the function?
public function getemailData()
{
$email_id_investors = $this->db
->select('value')
->get_where('common_email_settings', ['name' => investors_email])
->row()->value;
}
I wish to get the value of the $email_id_investors outside the function. Again I am apologizing for this basic question
Database table name - common_email_settings
fields are Id, title, name, value
1 Greeting Mail, greeting_email ,Greetings#investorsloanservicing.com
2 Loan Service Mail, loan_service_email ,LoanServicing#investorsloanservicing.com
3 Processing Mail, processing_email ,processing#investorsloanservicing.com
To strictly answer the question, you could store the value in a scoped global $this variable, though I don't know why you wouldn't just query the function and have it return a value.
public function getemailData($investors_email)
{
$this->email_id_investors = $this->db
->select('value')
->get_where('common_email_settings', ['name' => $investors_email])
->row()->value;
}
// then in another function called later in the chain, you can grab it
public function doSomethingElse() {
$investors = $this->email_id_investors;
}
It's probably better just to create a getter function for that variable.
This doesn't look useful given your scenario. This might be useful if the variable you're storing is something processor intensive (and you're using $this like a cache), you need to access it in multiple functions called during a given state, and you don't want to rewrite your function chain to accept this parameter (so as to pass it along). However, that is a clear sign you need to refactor your logic and make it more flexible (pass object or arrays rather than single variables for example).
You are not returning your variable.
Try returning your variable like this,
public function getemailData()
{
$email_id_investors = $this->db
->select('value')
->get_where('common_email_settings', ['name' => investors_email])
->row()->value;
return $email_id_investors;
}
function getemailData($name)
{
$email_id_investors = $this->db
->get_where('common_email_settings', ['name' => $name])
->result()[0];
return $email_id_investors->value;
}
This one worked for me. I have given this function in the common model page and called this on other pages.Thank you for your help
$email = $this->common->getemailData('account_email'); -> getting data in this variable
echo $email;
// exit();

Accessing session data in controller(Laravel)

I have a page 'A'. I create a session variable on this page.
This page is then redirected to a function 'A' in a controller 'A' using window.location.
I try to access the session variable in the function 'A' using the following line
var_dump($request->session->get('variableSetOnPageA'));
This returns NULL.
Why? I need the 'variableSetOnPageA'.
You can also get Session variable in Laravel like below in any of your function in Controller file:
$value = Session::get('variableSetOnPageA');
And you can set your Session variable like below in any of your function:
$variableSetOnPageA = "Can be anything";
Session::put('variableSetOnPageA',$variableSetOnPageA);
In your Controller file, make sure you add below code at top:
use Session;
You ought to invoke the session method from \Illuminate\Http\Request:
$request->session()->get('foo')
or global helper function
session('foo')
Important: It is very important that you call save function after you set any session value like this:
$request->session()->put('any-key', 'value');
$request->session()->save(); // This will actually store the value in session and it will be available then all over.
Check if you have $request available in the function.
public function A(Request $request) // Notice Request $request here.
{
$value = $request->session()->get('your-key');
//
}
This might be help you
if (session()->has('variableSetOnPageA')) {
$result=session()->get('variableSetOnPageA')
}

Basic Laravel route filtering with multiple parameters

So I'm attempting to authenticate my user's using Laravel's custom filters. I have my LDAP PHP script working and I have essentially plugged it in to my custom filter. However, I need to pass this script the username and password that the user enters on the log in screen; in other words, I need to pass my custom filter this username and password from the log in form.
Here is my code to help explain my problem:
routes.php
Route::group(array('before' => 'ldapTest'), function() {
Route::controller('apps', 'AppController', array(
//named routes here
));
});
filters.php
Route::filter('ldapTest', function()
{
$username = //how do I get this?
$password = //how do I get this?
//LDAP logic goes here; assume $ldapConn and $userDN are properly initialized
$userBind = #ldap_bind($ldapConn, $userDN, $password);
if($userBind)
{
Auth::login(//what goes here? I want to access $username later on in applications);
return Redirect::to('apps/home');
}
else
{
echo 'Incorrect password';
}
});
From reading the documentation I understand you can pass parameters as strings to filters like so: Route::filter('ldapTest:400', function(), but I don't understand how I could use this to pass my username and password using what I assume would be Input::get().
How can I do this?
Actually you can pass parameters into your custom filter and in this case your filter should look like this:
Route::filter('ldapTest', function($route, $request, $param){
//...
});
In your Closure the third argument will receive the parameter you passed in and it's $param, so you are able to pass it like this in your before filter:
array('before' => 'ldapTest:someString')
So, in the filter, the $param will contain someString but in your case that would be a bit different I think, because you want to receive the user inputs submitted through a form so to get those inputs you may use something like this in your filter's handler (Closure):
$username = $request->get('username'); // Assumed that username is a form field
$password = $request->get('password');
Also you may use Input::get('username') instead of $request if you want but it'll be working with $request instance variable and I would prefer that to use.
I had a similar needing in my project, solved with this (not so much elegant but working) workaround:
Route::filter('multiParamFilter', function($route, $request, $params){
list($p1, $p2) = explode(':', $params);
//Now you have $p1 and $p2 initialized with parameters
....
}
In routes.php you can call:
Route::get('path', array('before' => 'multiParamFilter:p1:p2' ......
Note: It requires that you dont use ':' (or at least another symbol) in your parameter values

Get value of custom user field in Drupal 7 template?

I'm building my first site with drupal. And I made a custom user field: Full name.
Now I want to get the value of this fild in my template to say “Hello, %username%”.
How do I do that?
Clive's answer is correct except that you should use field_get_items to get the values for a field. It will handle the language for you. You should also sanitize the value.
function THEME_preprocess_page() {
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$full_names = field_get_items('user', $user, 'field_full_name');
if ($full_names) {
$vars['full_name'] = check_plain($full_names[0]['value']);
}
}
If your site uses the Entity API module, you can also use a entity metadata wrapper like this
function THEME_preprocess_page() {
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$wrapper = entity_metadata_wrapper('user', $user);
$vars['full_name'] = $wrapper->field_full_name->get(0)->value(array('sanitize' => TRUE));
}
See also Writing robust code that uses fields, in Drupal 7
Depending on your setup/field name, something like this in template.php (preprocess function for the template file):
function mytheme_preprocess_page() {
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$vars['full_name'] = $user->field_full_name[LANGUAGE_NONE][0]['value'];
}
Then something like this in page.tpl.php:
if (isset($full_name) && !empty($full_name)) :
echo 'Hello ' . $full_name;
endif;
Note that LANGUAGE_NONE may need to be changed if you're running a multi-lingual site.
I know this question was asked quite a while ago, but I wanted to post an alternative. It looks like you want to change the field in the $variables array that is $variables['name'] to what you have in your custom field that I've called field_real_name. If you are using a preprocess function, there is no need to pull in the global $user object. You have access to the $variables array, so you can get the user information with this - it will load the information associated with the uid (see template_preprocess_username):
function mythemename_preprocess_username(&$variables) {
$account = user_load($variables['account']->uid);
...more code will go here in a moment
}
If you dpm($account) (or kpr($account) if you aren't using devel) you will see that you have access to all of the user information, without using the global $user object.
Then you can change the output of $variables['name'] to be your field_real_name as follows:
function mythemename_preprocess_username(&$variables) {
// Load user information with user fields
$account = user_load($variables['account']->uid);
// See if user has real_name set, if so use that as the name instead
$real_name = $account->field_real_name[LANGUAGE_NONE][0]['safe_value'];
if (isset($real_name)) {
$variables['name'] = $real_name;
}
}
We can add the below code anywhere in the template file.
<?php
global $user;
$user = user_load($user->uid);
print $user->name;
?>

How to convert an existing PHP library file so it can be used in a CakePHP framework?

I have this library in PHP non-Cake format, the usual PHP scripting which currently works like a charm. I need to use this in a Cake framework. The library file is as follow: (example extracted)
<?php
// REST API functions
function sendAction($itemurl, $itemimageurl, $sessionid, $userid, $rating=""){
global $someapiwebsiteURL, $apiKey, $tenantId;
$somewebsiteAPI = $someapiwebsiteURL.$action."?apikey=".$apiKey.
.....
................
}
//Codes extract
?>
I've come across a few ways of doing it. Currently confused, how am I going to place this library file into my Cake framework?
App::import()
Datasource
The functions in the library file above (I supposed it'd be used in one of my Controllers to render the data outputting through the view).
Currently working in a non-Cake framework structure, the view page is such as: (example extracted)
<?php
// my view page
$viewResponse = sendAction($itemdescription ,$itemurl , $itemimageurl,$sessionid,$userid);
//sample code only
?>
Both the files are working fine. The logic of putting it in a CakePHP framework is the problem here. Anyone may suggest "the" way of doing this without over-strenuously working on a data source? If we have to use a data source in App/models/datasources/, how exactly is the structure of it? Like, e.g., in datasource file, do we include the library functions? or is it some generic ReST datasource file which can be found here: CakePHP ReST datasource . I've gone through the cookbook chapter on datasource and understand we have to define the datasource in our database.php, but if someone is certain about their way of accomplishing it either using datasource or app::import() method, please share with more details?
UPDATE:
Hi Lionel!, thanks for filling up. Well, actually users will click on view action: function view (){} in my foods_controller. I'm appending some scripts here to include my view function in my foods_controller so maybe it may help you to help out easier. Thanks..
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid food', true));
$this->redirect(array('action' => 'index'));
}
$this->set('food', $this->Food->read(null, $id));
}
The view action triggers the send_action function, (each time a user clicks on view page on foods controller). So each time, a user clicks on view action, his (dynamic variables): userid, sessionid, that page's itemid, url, itemdescription; (timerange value is a static string value "ALL"), and if any (etc.), so far only these values are available: Will be used as the "parameters" in the Send Action function. What you wrote is close to what the codes can do. You're right. Except we should include the Send Action function inside the view() in foods controller?
If we look at dynamically filling in the variables mentioned in the point above, could you modify your second code (the code from your product_controller, e.g.) so it also works to receive the variables dynamically? (as you asked in the last update: how to get the parameters..)
Just to make it clear.
A user views the page. The send action collects data and send to the API. (as we've already done by calling the function in the library the (ACME.php). *just waiting for your update if possible, thanks.
In the function view() of the foods controller: there's also an additional calling. The (2)second calling which is this:
$recommendResponse = getRecommendations("otherusersviewed", $itemId, $userId);
The second calling calls the ACME.php library file in which there consists the (2)second function that retrieves data, here it is: (it's in working order, but just needs to be changed into a public static function like you did for the (1)first function. Could you help to modify this code too, please?:
function getRecommendations($recommendationType, $itemId, $userId){
// sample code similar to the first one.
}
That's all to it. It seems quite simple in the normal PHP format, and it works easily, but getting it on an MVC framweork is a bit challenging for some, a lot for me. Thanks for helping out, Lionel. :-)
P.S. Hi Lionel, I notice something missing in the library after changes? Look originally we have this:
$somewebsiteAPI = $someapiwebsiteURL.$action."?apikey=".$apiKey.
Look, the variables for $SomeWebsiteAPI and $SomeApiWebsiteURL are different. Did I miss out something? or you have modified so it is more efficient ? I see that the variable named $SomeWebsiteAPI is modified to become variable called $link ? and variable $SomeApiWebsiteURL is changed to the named variable, $url, am I right ? .. thanks.
Thanks, best regards. John Maxim
To me, if I have this piece of code, I would first wrap it into a static (or normal) class, and named it ACME, then I will move the acme.php into /apps/libs/acme.php. Then in the controller, I will use App::import('Lib', 'acme'). This action do nothing but just requiring the file, so you can just use it instantly by calling ACME::sendAction(...).
And regarding the global thing, you might just need to declare a static (or normal) class, then define the shared variables as part of the class properties, so you can share them among all the functions in the class.
For example, this is the /app/libs/acme.php
class ACME {
private static $someapiwebsiteURL = "http://thewebsite/api/1.0/";
private static $apiKey = "0010KIUMLA0PLQA665JJ";
private static $tenantId = "THE_TENANT_NAME";
/**
* Simple builder to build links from array of $params
*
* #param string $url The api url
* #param array $params The given parameters
* #return string built url
*/
private static function BuildLink($url="", $params=array()) {
$link = $url;
foreach($params as $k=>$v) {
$link .= "&$k=$v";
}
//Replace the first & to ?
$link = preg_replace("/&/", "?", $link, 1);
//Not sure if we need URL encode here, please uncomment this
//if the API could not work.
//$link = urlencode($link);
return $link;
}
public static function SendAction($action, $itemId, $itemdescription, $itemurl, $itemimageurl, $sessionid, $userid, $rating="") {
$somewebsiteAPI = self::BuildLink(self::$someapiwebsiteURL.$action, array(
"apikey"=>self::$apiKey,
"sessionid"=>$sessionid,
"userid"=>$userid,
"tenantid"=>self::$tenantId,
"itemid"=>$itemId,
"itemdescription"=>$itemdescription,
"itemurl"=>$itemurl,
"itemimageurl"=>$itemimageurl,
/**
* Assuming your API smart enough to only use this value when
* the action is "rate"
*/
"ratingvalue"=>$rating
));
$xml = simplexml_load_file($somewebsiteAPI);
return $xml;
}
public static function GetRecommendations($recommendationType, $itemId, $userId) {
$somewebsiteAPI = self::BuildLink(self::$someapiwebsiteURL.$recommendationType, array(
'apikey'=>self::$apiKey,
'tenantid'=>self::$tenantId,
'itemid'=>$itemId,
'userid'=>$userId
));
$xml = simplexml_load_file($somewebsiteAPI);
return $xml;
}
}
And in your controller
App::import('Lib', 'acme');
class FoodController extends AppController {
//Food is plural already I assume? You can just use
//food, should be ok I think, else it will be weird
//to use /foods/view/?
var $name = "Food";
var $uses = array("Item", "Food");
function view($id="") {
//We accepts only valid $id and $id > 0.
//Take notes that this $id will be a string, not int.
if (ctype_digit($id) && $id > 0) {
//I don't know how you would gather the information, but I assume you
//have a database with the information ready.
//I assumed you have an `items` table
$item = $this->Item->findById($id);
$sessionid = "00988PPLO899223NHQQFA069F5434DB7EC2E34"; //$this->Session->...?
$timeRange = "ALL";
$userid = "24EH1725550099LLAOP3"; //$this->Auth->user('id')?
if (!empty($item)) {
$desc = $item['Item']['description'];
$url = "/foods/view/".$id;
$img = $item['Item']['img'];
$viewResponse = ACME::SendAction("view", $id, $desc ,$url, $img, $sessionid, $userid);
$this->set('food', $this->Food->read(null, $id));
}else{
$this->Session->setFlash(__('Invalid food', true));
$this->redirect(array('action' => 'index'));
}
}else{
$this->Session->setFlash(__('Invalid food', true));
$this->redirect(array('action' => 'index'));
}
}
}
Edit
The code has been filled up, and of course, without any warranty :). I personally don't really like to have long arguments in a function (like SendAction, error prune), rather use shorter one like the $params in ACME::BuildLink. But just to respect your code, I didn't modify much on the SendAction method.
Then I'm not too sure how you would make use of this code, so I assumed you have a ProductsController, and somehow the user trigger url like /products/send_action/. If you can provide more information, then we would be able to help out.
Edit Again
I have modified the ACME class, as well as the controller. Yea I do miss out some variables, but I had added them back to the updated code.
Not too sure if it would work (perhaps typo), you can just modify the code if it doesn't work for you.
And for personal conventions, I usually capitalize methods which are static, like ACME:GetRecommendations or ACME::SendAction.
Oh yea, I better stick back to the variables you used. Sorry for modifying them, just I don't like long names :)
And btw, the RoadRunner's ACME Corporation? Lol!
Cheers
Lionel

Categories