How can I access the variables which are set to the view in CakePHP 3 in a Helper? I did not find anything in the documentation.
In CakePHP 2.x this used to work:
$this->_View->viewVars['foo'];
Reading the API helps.
655: /**
656: * Returns the contents of the given View variable.
657: *
658: * #param string $var The view var you want the contents of.
659: * #param mixed $default The default/fallback content of $var.
660: * #return mixed The content of the named var if its set, otherwise $default.
661: */
662: public function get($var, $default = null)
663: {
664: if (!isset($this->viewVars[$var])) {
665: return $default;
666: }
667:
668: return $this->viewVars[$var];
669: }
Related
Just wondering what is the difference between:
$username = $request->input('username');
and
$username = Input::get('username');
There is no difference, the facade Input calls the input method from request. But Input::get is deprecated, prefer the $request->input instead of Input::get
<?php
namespace Illuminate\Support\Facades;
/**
* #see \Illuminate\Http\Request
*/
class Input extends Facade
{
/**
* Get an item from the input data.
*
* This method is used for all request verbs (GET, POST, PUT, and DELETE)
*
* #param string $key
* #param mixed $default
* #return mixed
*/
public static function get($key = null, $default = null)
{
return static::$app['request']->input($key, $default);
}
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'request';
}
}
Both are the same but this one kind laravel inbuilt Functionality To make a proper use of laravel.
You can use both way but following things are made only in INPUT. Just a look.
Input::has('name')
Input::all()
Input::only('username', 'password')
Input::except('credit_card')
Input::get('products.0.name')
And also this on
Input::get('username');
So that make things easy for as.
That other thing we have to do more code if we use this.
$request->input('username')
Hope You understand.
Thanks.
As the documentation says the function Redirect::action() receives a string which is separated into 2 parts by the symbol #
The controller name
The method name
e.g. Redirect::action('MyController#myFunction')
I've recently tried to give the function an input: Redirect::action('someRouteName') and see what's gonna happen. Surprisingly it didn't return with an error but actually made the link just as if I was using the Redirect::route() function (I had a route named as someRouteName).
Does the function Redirect::action() falls back to Redirect::route() if the value it gets is invalid? Couldn't find any source that says that.
Yes, it does. Some insight on it can be seen in sources.
https://github.com/laravel/framework/blob/master/src/Illuminate/Routing/UrlGenerator.php#L455
/**
* Get the URL to a controller action.
*
* #param string $action
* #param mixed $parameters
* #param bool $absolute
* #return string
*/
public function action($action, $parameters = array(), $absolute = true)
{
return $this->route($action, $parameters, $absolute, $this->routes->getByAction($action));
}
In my php application I have been comparing objects with the usual equality comparison operator, e.g.:
if ($objectA == $objectB) { ... }
Recently I implemented proxies (for objects which are expensive to load) however this means the equality operator no longer works. Is there a simple way around this? One that doesn't rely on reflection?
For the moment, I have resorted to testing the unique identifier of each object, e.g.
if ($objectA->getId() == $objectB->getId) { ... }
But this has two problems: 1) I need to refactor all existing code, and 2) in the future I may need to compare objects which are value objects (not entities).
I'm not hopeful of an easy solution since I think it would require a new magic method...
Here's my AbstractProxy class. Any help appreciated...
abstract class KOOP_Base_AbstractProxy
implements KOOP_Base_iDomain
{
use KOOP_Trait_Helper_Helper;
/**
* #var integer Object identifier
*/
protected $_id = null;
/**
* #var KOOP_Base_AbstractMapper
*/
protected $_mapper = null;
/**
* #var KOOP_Base_AbstractDomain Actual object
*/
protected $_subject = null;
/**
* Store object id for lazy loading
*
* #param integer $id Object identifier
* #param string $mapper Mapper by which to retrieve object
*/
public function __construct($id, $mapper)
{
$this->_id = $id;
$this->_mapper = $mapper;
}
/**
* Get subject
*
* #return KOOP_Base_AbstractDomain
*/
protected function getSubject()
{
if (!$this->_subject) {
$this->_subject = $this->getMapper($this->_mapper)->find($this->_id);
}
return $this->_subject;
}
/**
* Get property
*
* #param string $property
* #return mixed
*/
public function __get($property)
{
return $this->getSubject()->$property;
}
/**
* Set property
*
* #param string $property
* #param mixed $value
* #return void
*/
public function __set($property, $value)
{
$this->getSubject()->$property = $value;
}
/**
* Is property set?
*
* #param $property
* #return boolean
*/
public function __isset($property)
{
return isset($this->getSubject()->$property);
}
/**
* Unset property
*
* #param string $property
* #return mixed
*/
public function __unset($property)
{
unset($this->getSubject()->$property);
}
/**
* Call method
*
* #param string $method Method to call
* #param array $params Parameters to pass
* #return mixed
*/
public function __call($method, array $params)
{
return call_user_func_array(array($this->getSubject(), $method), $params);
}
/**
* Get id
*
* Saves having to retrieve the entire object when only the ID is required.
*/
public function getId()
{
return $this->_id;
}
}
Proxies do break object equality, and there's no utterly clean way to fix this. In a fully object oriented language you would handle this by operator overloading (which I don't recommend) or implementing a custom .equals() function (as in Java). Sadly, PHP simply does not support object orientation at this level, so you will have some decisions to make.
1) I would prefer to have your proxy class provide an equals() function which takes as input a reference to the object you want to test against and compares it to the proxied object - which shouldn't be much more 'expensive' than it was to not use a proxy at all. Example in pseudo-PHP code (my apologies if my reference syntax is off, it's been a while):
public function equals (&$toCompare)
{
if ($_subject == $toCompare)
{
return true;
}
else
{
return false;
}
}
The downside is simple: you have to refactor your code that involves this proxied object, and you have to remember that "==" does not work on this proxied object type while you are working. If you don't deal with these objects much, or if you deal with them all the time, this is fine. If you deal with them regularly but intermittently, or if others must work with them on occasion, then this will cause bugs when you/they forget about this equality problem.
2) Use an Operator Overloading extension to the language. I haven't done this, I don't know if it works, and it might be a nightmare. I include it for theoretical completeness.
Personally, I think I'd just hack it with the pseudo-Java approach call it a day, as I think it would actually work and require nothing more than using the function correctly (and remembering to use it in the first place).
Is it possible to make all function's vars global without typing all of them like global $a, $b, $c...?
Try creating a Static object within your application and assigning variables to that scope, Like so!
<?php
/*
* Core class thats used to store objects of ease of access within difficult scopes
*/
class Registry
{
/*
* #var array Holds all the main objects in an array a greater scope access
* #access private
*/
private static $objects = array();
/**
* Add's an object into the the global
* #param string $name
* #param string $object
* #return bool
*/
public static function add($name,$object)
{
self::$objects[$name] = $object;
return true;
}
/*
* Get's an object out of the registry
* #param string $name
* #return object on success, false on failure
*/
public static function get($name)
{ if(isset(self::$objects[$name]))
{
return self::$objects[$name];
}
return false;
}
/**
* Removes an object out of Registry (Hardly used)
* #param string $name
* #return bool
*/
static function remove($name)
{
unset(self::$objects[$name]);
return true;
}
/**
* Checks if an object is stored within the registry
* #param string $name
* #return bool
*/
static function is_set($name)
{
return isset(self::$objects[$name]);
}
}
?>
Considering this file is one of the first files included you can set any object/array/variable/resource/ etc into this scope.
So lets say you have just made a DB Connection, this is hwo you use it
...
$database = new PDO($dns);
Registry::add('Database',$database);
$DBConfig = Registry::get('Database')->query('SELECT * FROM config_table')->fetchAll(PDO::FETCH_CLASS);
Registry::add('Config',$DBConfig);
No anywhere else within your script you can add or retrieve items.
with Registry::get('ITEM_NEEDED');
This will work in methods functions etc.
Perfect example
function insertItem($keys,$values)
{
Registry::get('Database')->query('INSERT INTO items ('.implode(',',$keys).') VALUES ('.implode(',',$values).')');
}
Hope it helps
No. That'd be an awful thing to do anyways.
You can pass them as arguments and then you won't need the global keyword:
function(&$a, &$b, &$c)
{
// your code........
}
You can always use $GLOBALS["var"] instead of $var. Of course, if you need this, you're most likely doing it wrong.
Does PHP have a method of having auto-generated class variables? I think I've seen something like this before but I'm not certain.
public class TestClass {
private $data = array();
public function TestClass() {
$this->data['firstValue'] = "cheese";
}
}
The $this->data array is always an associative array but they keys change from class to class. Is there any viable way to access $this->data['firstValue'] from $this->firstValue without having to define the link?
And if it is, are there any downsides to it?
Or is there a static method of defining the link in a way which won't explode if the $this->data array doesn't contain that key?
See here: http://www.php.net/manual/en/language.oop5.overloading.php
What you want is the "__get" method. There is an example for what you need on the link.
Use the PHP5 "magic" __get() method. It would work like so:
public class TestClass {
private $data = array();
// Since you're using PHP5, you should be using PHP5 style constructors.
public function __construct() {
$this->data['firstValue'] = "cheese";
}
/**
* This is the magic get function. Any class variable you try to access from
* outside the class that is not public will go through this method. The variable
* name will be passed in to the $param parameter. For this example, all
* will be retrieved from the private $data array. If the variable doesn't exist
* in the array, then the method will return null.
*
* #param string $param Class variable name
*
* #return mixed
*/
public function __get($param) {
if (isset($this->data[$param])) {
return $this->data[$param];
} else {
return null;
}
}
/**
* This is the "magic" isset method. It is very important to implement this
* method when using __get to change or retrieve data members from private or
* protected members. If it is not implemented, code that checks to see if a
* particular variable has been set will fail even though you'll be able to
* retrieve a value for that variable.
*
* #param string $param Variable name to check
*
* #return boolean
*/
public function __isset($param) {
return isset($this->data[$param]);
}
/**
* This method is required if you want to be able to set variables from outside
* your class without providing explicit setter options. Similar to accessing
* a variable using $foo = $object->firstValue, this method allows you to set
* the value of a variable (any variable in this case, but it can be limited
* by modifying this method) by doing something like:
* $this->secondValue = 'foo';
*
* #param string $param Class variable name to set
* #param mixed $value Value to set
*
* #return null
*/
public function __set($param, $value) {
$this->data[$param] = $value;
}
}
Using the magic __get, __set, and __isset constructors will allow you to control how you want variables to be set on a class while still storing all the values in a single array.
Hope this helps :)