Laravel Class/Controller level variable doesnt get update from Method - php

I have this variable on class/Controller level $songRating and i am calling this method through ajax, when i first time call this method it runs the if block which is good. and now $songRating should be 1.
But this is not a case. When i call this method it again runs the if block. Dont know why :/
public $songRating;
public function GetHighRatedSong()
{
if($this->songRating == null){
$this->songRating=1;
}else{
$this->songRating=2;
}
return response()->json($this->songRating);
}

Try with Replacing
$this->songrating=1;
to
$this->songRating=1; # song+Rating != song+rating
Read PHP & Case Sensitivity

It's because everytime you call that function or make a new instantiation to the class, it will automatically reset to it's original value. Try to use service container

Related

How to assert input on a chained mock method

Im using PHPunit 8.3.5 and I'm trying to check wether a method gets the right parameter.
Example code:
$this->registry->get($thing)->apply(EXAMPLE::SUBMIT);
$this->registry->get($thing)->apply(EXAMPLE::CANCEL);
I have two functions, functionA uses the first example line, functionB the second. I need to make sure functionA uses SUBMIT and nothing else, and the same for Bs case.
The problem:
I can use a ->method('apply')->with() with a callback to test wether it gets the right input
I can create a willReturn for ->method('get')->with() to return a simple class with apply as function
I can't figure out how to combine the two
$registryMock = $this->createMock(Registry::class);
$registryMock->method('get')->willReturn(new class {
public function apply(){} // <-- I need to assert the input of this method
});
$registryMock->method('apply')->with(self::callback(function($order, $status){
return $status === EXAMPLE::SUBMIT;
}));
How can I combine those two methods? I've also tried get->apply, but that wasnt it.
Please note: Rewriting the actual code is not an option.
Based on the comment of Dirk:
You create a mock first the 2nd function like you would normally. You then create a mock that returns the previous mock:
// first we create a mock for the last in the chain, here '->apply()'
$registryMockApply = $this->createMock(Registry::class);
$registryMockApply->expects(self::once())->method('apply')->with(
self::equalTo(EXAMPLE::SUBMIT),
);
// Then the one before that, here '->get()', which returns the previous mock
$registryMock = $this->createMock(Registry::class);
$registryMock->method('get')->willReturn($registryMockApply);
// Together resulting in '->get()->apply()'

CodeIgniter 4 redirect function not working

After logout, I tried to redirect for the home page. I tried to few ways, but not redirected.
class User extends BaseController
{
public function __construct()
{
helper('url');
}
for the logout function. I used three ways
redirect('/');
or
header("Location:".base_url());
or
route_to('/');
as per CI 4
use
return redirect()->to('url');
if you are using route then use
return redirect()->route('named_route');
I use this and it works
return redirect()->to(site_url());
In codeigniter 4 redirect()->to() returns a RedirectResponse object, which you need to return from your controller to do the redirect.
for ex.
class Home extends BaseController {
public function index() {
return redirect()->to('https://example.com');
}
}
I am new to CI4. In my case, I had to properly set $baseURL in App.php. For example, if the port is set incorrectly in your local development, it will just hang.
eg. public $baseURL = 'http://localhost:8888/';
Its worth saying that unlike the former CI3 redirect() function this one must be called from within a Controller. It won't work for example within a Library.
Update 2021
It is in fact possible to do this! Simply check that the returned response is an object and return it instead. So if a library returns a RedirectResponse, check it using the following code and return if applicable.
if (!empty($log) && is_object($log)){
return $log;
}
You could of course do get_class() to make sure the object is a type of RedirectResponse if there is any possibility of another object being returned.
If you using unnamed route:
$this->response->redirect(site_url('/user'));
'/user': It is my controller name. You can also used controller/function name.
Please look at the documentation
// Go back to the previous page
return redirect()->back();
// Go to specific URI
return redirect()->to('/admin');
// Go to a named route
return redirect()->route('named_route');
// Keep the old input values upon redirect so they can be used by the old() function
return redirect()->back()->withInput();
// Set a flash message
return redirect()->back()->with('foo', 'message');
// Copies all cookies from global response instance
return redirect()->back()->withCookies();
// Copies all headers from the global response instance
return redirect()->back()->withHeaders();
If you find:
{0, string} route cannot be found while reverse-routing
This error:
Please Go to system\HTTP\RedirectResponse Line no 91 :
Change:
throw HTTPException::forInvalidRedirectRoute($route);
To:
return $this->redirect(site_url('/Home'));
(dashboard after login)
The redirect statement in code igniter sends the user to the specified web page using a redirect header statement.
This statement resides in the URL helper which is loaded in the following way:
$this->load->helper('url');
The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file.
The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh".
According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem."
Example:
if ($user_logged_in === FALSE)
{
redirect('/account/login', 'refresh');
}
Original Answer: https://stackoverflow.com/a/725200/5700401

undefined variable error in blade view

I am currently working with Laravel 5.2, trying to display images on click
which I have currently stored in the Storage folder. I am trying to display these images in my blade view but every time it loads the page, it gets to an undefined variable exception.
Controller:
public function createemoji($action,$statusId)
{
$path = storage_path('app/public/images/'.$action.'.gif');
/*$request=new storage();
$request->comment=$path;
$request->user_id=Auth::user()->id;
$request->post_id=$statusId;
$request->save();*/
return redirect()->returnemoji()->with('file'->$path);
}
public function returnemoji($file)
{
return Image::get('$file')->response();
}
In my default view I tried using count() but everytime it loads the page, it gives me Undefined variable. How should I display it?
Try to change this:
->with('file'->$path);
To this:
->with('file', $path);
https://laravel.com/docs/5.3/views#passing-data-to-views
With function takes two arguments key and value
You can use this
return redirect()->returnemoji()->with('file',$path);
You can try this out:
Instead of:
return redirect()->returnemoji()->with('file'->$path);
Try this:
return $this->returnemoji($path);
Hope this helps you.
There are a few problems.
Single quotes do not process variables, so instead of this
return Image::get('$file')->response();
You could do this
return Image::get("$file")->response();
or
return Image::get("{$file}")->response();
but none of this is necssary since you are just using the variable by itself without any additional formatting, so remove the quotes altogether
return Image::get($file)->response();
The object operator -> is used in object scope to access methods and properties of an object. Your function returnemoji() is not a method of RedirectResponse class which is what the redirect() helper method returns.
The with() method is not appropriate here, you just need to pass a parameter to a function like this
return redirect()->returnemoji($path);
Optionally, I recommend following the PSR2 code style standard which includes camel cased variable names so createemoji() should be createEmoji(). Also I think you can usually omit response() when returning most data types in Laravel as it will handle that automatically for you.
I think you have to try the following:
Instead of:
return redirect()->returnemoji()->with('file'->$path);
Try this:
return redirect()->returnemoji($path);
And yes, remove the quotes from this:
return Image::get('$file')->response();

What are the available ways to check session's value throughout the website?

In my default controller session's value is set.
now in my every controller that calls different view, I wants to check if session's value is set then only that view will be shown otherwise it will redirect user to the log in view.
So, as per my knowledge I have to check session's value in my every controller is there any shortcut way?? or is there any way to call one file/function which is called every time before call of any controller. so I can check session's value there.
I had try via hook also like this :
class Authentication extends CI_Hooks {
var $CI;
function __construct() {
$this->CI = & get_instance();
}
public function verify_session() {
if (!isset($this->CI->session)) {
$this->CI->load->library('session');
$user_session_id = $CI->session->userdata('email');
if ($user_session_id == '') {
redirect('common_controller/home_controller');
}
}
}
}
but it shows me eroor like this : Severity: Notice
Message: Trying to get property of non-object
Filename: hooks/Authentication.php
Line Number: 20
You don't say what framework you're using, but I'm guessing that if you're using MVC that there is a single php file (usually index.php) where you can put your code.
Also it appears to use hooks so you could just add it to a hook that is executed before the controller is identified and called.
Just remember to add a check if you're on the login page and not to apply the redirect if so...
Try:
<script>
console.log(<?php echo json_encode($_SESSION, JSON_HEX_TAG); ?>);

How to reset class variables without reseting the current instance ones

I was unable to find a similar question on Stackoverflow, although I am sure someone has probably asked this before.
I have a class with methods that may be called several times per page. Each time the method is called I need to make sure the public variables are reset to their defaults, UNLESS they have been set before calling the method.
This cannot be achieved using a simple if condition because there is no way to tell whether the value has been set or is still set from the last method call
I cannot think of a way to achieve this because I cannot call my __construct method (which sets all the default values), as this would overwrite the parsed values. However, I need to reset them to prevent values from the last method call from being parsed.
The obvious answer is to give different names to the public variables and the return variables. I will do this if there is no other option but I like to keep the number of variables to a minimum
It is very hard to explain this in writing so I will update this question with an example of what I mean in code.
UPDATE
An example of where a problem may occur:
<?php
class test{
public $return_array;
public $return_string;
public $return_bool;
function __construct(){
// Set the default values
$this->return_array = false;
$this->return_string = false;
$this->return_bool = false;
}
public function method(){
// ... do something
$array = array('test');
$string = 'test';
$bool = true;
// Only return variables if asked to
$this->return_array = $this->return_array ? $array : NULL;
$this->return_string = $this->return_string ? $string : NULL;
$this->return_bool = $this->return_bool ? $bool : NULL;
return;
}
}
// Initiate the class
$test = new test;
// Call the method the first time with one parameter set
$test->return_array = true;
$test->method();
// Print the result
print_r($test->return_array);
// MOST OBVIOUS ANSWER WOULD BE TO RESET VARIABLES HERE LIKE SO
$test->reset(); // HOWEVER, I DO NOT WANT TO HAVE TO CALL THIS EACH TIME I CALL THE METHOD, HERE LIES MY PROBLEM!
// Call the method again with different parameters
$test->return_string = true;
$test->return_bool = true;
$test->method();
// Print the result
echo $test->return_array;
echo $test->return_bool;
/* The problem lies in the second call of the method because $test->return_array has not been reset to its default value. However, there is no way to reset it without affecting the other variables. */
?>
This is basically a very long winded way of asking whether it is possible to reset a classes variables to their default values, whilst ignoring the ones that have been parsed to the method being called
There are several ways to achieve this but they all bottle down to the same solution. Calling a function after each method that resets the variables within the class. Best way to do this is at the end of each method before the data is returned.

Categories