I have a function in my controller. I created a lot of variables, and send them to my view via compact function one by one.
public function edit($id,$cpe_mac) {
$vcpe = VSE::vcpe($cpe_mac);
$vcpe = json_decode (json_encode($vcpe), FALSE);
$cpe = VSE::cpe($cpe_mac);
$wan = $cpe['wan'];
$acl = $cpe['acl'];
$guest = $cpe['vlan'][0];
$private = $cpe['vlan'][1];
$cpe_name = VSE::cpe_name($cpe_mac)['cpe_name'];
$p_max_up = $private['bandwidth']['max_up'];
$p_max_down = $private['bandwidth']['max_down'];
$p_ip = $private['lan']['ip_address'];
$p_netmask = $private['lan']['netmask'];
$p_max_clients = $private['lan']['dhcp_server']['max_clients'];
$p_dns = $private['lan']['dhcp_server']['dns'][0];
$p_dns2 = $private['lan']['dhcp_server']['dns'][1];
$cpe = json_decode (json_encode($cpe), FALSE);
return view('cpe.edit', compact(['vcpe','cpe_mac','cpe_name','cpe','wan','acl','private','guest',
'p_max_up','p_max_down','p_ip','p_netmask','p_max_clients','p_dns','p_dns2'
]));
}
Question
Is there a way to send all the variables to the view rather than doing it one by one ?
You could do the following...
return view('cpe.edit', get_defined_vars());
There might be some unnecessary overhead though if you are creating a lot of variables which you would not otherwise need in your view.
To simplify you can do this
// BaseController
protected $data = array();
// Controller
$this->data = array(
'variable' => $variable,
// ...
);
return View::make('example', $this->data);
But I dont think there is more simpler way or I am not aware.
You could use an array to send all the variables to the view.
Related
I'm trying to adapt a class of mine that handles tags for events stored in a JSON file. You can create tags, delete them, restore them, view them, etc. In the code below for this library you can see that I retrieve the array from the file during the constructor function so I use it and manipulate it throughout my classes' functions.
class tagHandler {
private $tagsFile = "/home/thomassm/public_html/functions/php/tags.json";
private $LstTags;
private $LstReturn;
function __construct() {
$this->LstTags = array();
if(!file_exists ($this->tagsFile)){
$fHND = fopen($this->tagsFile, "w");
$tmpArray = array(array("EID","EName","EColor", "EDel"));
fwrite($fHND, json_encode($tmpArray));
fclose($fHND);
}
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
function __destruct(){
$this->update();
}
public function update(){
$this->LstTags = array_values($this->LstTags);
$fHND = fopen($this->tagsFile, "w");
fwrite($fHND, json_encode($this->LstTags));
fclose($fHND);
//empty memory region
$this->LstTags = array();
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode($encodedInput[0], true);
}
//More functions that use the collected array here.
I am trying to adapt the class to deal with people signed up to my events. Each event has a record in my database that will store a field for an array of males who sign up and females who sign up. I wish for the constructor class to get the arrays(s) from the record so they can be manipulated like the previous class. The issue is to get the array I have to search the DB for a record with the Event ID (EID) and that will require a variable passed to the constructor function. To make things worse, this parameter has to be able to change in a loop. For example, the page listing all the events will have to use this class in a loop going through each record, so it can retrieve the array to manipulate it and then show it in a table / fullcalendar before repeating the process to get the next event. I have put the code I have so far below. Its not complete (some variables haven't been renamed to male and female, etc) and may be completely wrong, but it will give you a base to explain from.
class signupHandler {
private $LstMaleS;
private $LstFemaleS;
private $LstReturn;
function __construct($IntEID) {
$this->LstTags = array();
$StrQuery = "SELECT MaleS, FemaleS FROM tblEvents WHERE EID = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('s',$IntEID);
$statement->execute ();
$results = $statement->get_result ();
}
$this->LstTags = json_decode($encodedInput[0], true);
if(!$this->LstTags) $this->LstTags = array();
}
Thanks,
Tom
function decodeNames($StrNames){
$this->LstNames = array();
$this->LstNames = json_decode($StrNames, true);
if(!$this->LstNames) $this->LstNames = array();
$this->LstNames = array_values($this->LstNames);
}
function update(){
$this->LstNames = array_values($this->LstNames);
return json_encode($this->LstNames);
}
public function addSignUp($StrNames, $StrUsername, $StrStatus){
$this->decodeNames($StrNames);
$BlnPresent = false;
for($i = 0; $i < count($this->LstNames); $i++){
if($this->LstNames[$i][0] == $StrUsername){
$this->LstNames[$i][1] = $StrStatus;
$BlnPresent = true;
}
}
if($BlnPresent == false){
array_push($this->LstNames, array($StrUsername, $StrStatus, date("Y-m-d H:i:s")));
}
return $this->update();
}
I have decided to pass the encoded JSON array to the class each time I call a function from it. Before every function it is decoded and turned into an array and at the end it is then re-encoded and returned back to the file calling it. Now I no longer have any constructor or destruct functions.
I am having a problem with this variable "admin_user_id".. i want to set the val of the var in one function and use that var value in other function here..
But problem is that it gives null. i think its bcz of diff reference of the class..
class ChangeRequestProcessController extends AppController{
static $admin_user_id;
public function ajax_list_of_change_request(){
$this->autoRender = false;
$params = array();
$params[] = $this->Auth->user('id');
//debug($params);
$result = $this->AppProcess->callProcedure('ListOfChangeRequestProcess', $params);
//echo("here:"+$result);
$admin_user_id=$params[0];
//debug( $this->admin_user_id);
echo json_encode($result);
}
public function application_attachment_upload_with_title() {
$this->autoRender = FALSE;
$attachment_array[]=$this->admin_user_id;///p_admin_user_id
//$attachment_array[]="name";///p_uploaded_by
$attachment_array[]=$_POST['title'];///p_attachment_title
// $attachment_array[] = $loged_on_id;
//$attachment_array[] = $_FILES[0]['name'];
//$attachment_array[] = $_POST['title'];
debug($attachment_array);
$result = $application->AttachmentTemp->callProcedure('ChangeRequestAttachmentFinalAddWithTitle', $attachment_array);///call procedure
echo json_encode($result);///result
}
how to solve this problem in php so that the value persists(i think static var will solve it..but it also gives undefined var error inside function)???
Thanks in advance
(this doesn't fit the comment box, so here i go...)
Assuming
// your code to get this...
$admin_user_id = $params[0];
You can store it in a session using this:
if(!session_id()){
session_start();
}
$_SESSION['admin_user_id'] = $admin_user_id; // again, assuming this is the value!
To read it (in your second call/method), simply do:
if(!session_id()){
session_start();
}
$admin_user_id = $_SESSION['admin_user_id'];
For more info, see the php.net: sessions and $_SESSION
Can someone please introduce a more efficient or proper way of assigning variables in php?
Here is a snippet of my code:
class PurchaseController extends BaseController
{
/**
*Gets input form form
*
*#var input
*/
protected $input;
public function postPurchaseCheck()
{
$input = Input::all();
$this->input = $input;
if form submit button has value "buy" then use postPurhcase method
if (Input::get('buy')) {
$this->postPurchase();
}
elseif (Input::get('cart')) {
$this->postAddCart();
}
}
public function postAddCart()
{
//Add these items to cart
echo "Add these items to cart";
$memory = $this->input['memory'];
$color = $this->input['color'];
$size = $this->input['size'];
$price = $this->input['price'];
$battery = $this->input['battery'];
$accessories = $this->input['accessories'];
.........etc
}
public function postPurchase()
{
//Get prices, item id, etc and send user to checkout page
$memory = $this->input['memory'];
$color = $this->input['color'];
$size = $this->input['size'];
$price = $this->input['price'];
$battery = $this->input['battery'];
$accessories = $this->input['accessories'];
.........and so forth. I was wondering if there is a faster way of doing this in php without having to reassign variables for each method
}
}
You could do it like the following code, will save a few lines...
<?php
//loop an expected array, check and set from input
foreach(array('memory','color','size','price','...') as $key){
$$key = isset($this->input[$key]) ? $this->input[$key] : null;
}
?>
$$key = http://php.net/manual/en/language.variables.variable.php
But you may as well use $this->input['memory'] ect, instead of reassigning them to local variables.
Also your doing, which is basically just wasting memory (same as above):
$input = Input::all();
$this->input = $input;
Just do: $this->input = Input::all();
You can use the extract method but I would be cautious about this function with input. Pretty much you will be putting yourself back to Register globals.
http://php.net/manual/en/function.extract.php
http://php.net/manual/en/security.globals.php
Why can't use the value directly from the input?
Hi all I'm using zend framework (but I think this is irrelevant) and php5 and I just want to modify an object of an object
public function saveSite($post) {
$form = new Diff_Form_Download();
$subform = new Diff_Form_DownloadSubform();
$form = $this->view->form;
$newSite = 0;
$sitesRecord = new Diff_Model_Sites();
$debugString = null;
if (is_array($post)) {
$subform = $this->getSubformByPost($post);
$debugString = $subform->getContent();
echo $debugString;
//new site instertion
if (is_null($subform)) {
$subform = $form->getSubForm('NewSite');
$newSite = 1;
}
$values = reset($subform->getValues());
$sitesRecord = Doctrine_Core::getTable('Diff_Model_Sites')->findOneBy('idSite', $values['idSite']);
if ($sitesRecord) {
$sitesRecord->idSite = $values['idSite']; //useless but necessary to make Doctrine understand to use update?
} else { //if the record is not present instantiate a new object (otherwise save() will not work
$sitesRecord = new Diff_Model_Sites();
}
$sitesRecord->content = $subform->getContent(); //$values['content'];
$sitesRecord->newHtml = $subform->getContent();
$sitesRecord->url = $values['url'];
$sitesRecord->shortName = $values['shortName'];
$sitesRecord->lastChanged = date("Y-m-d H:i:s");
$sitesRecord->pollingHours = $values['pollingHours'];
$sitesRecord->minLengthChange = $values['minLenghtChange'];
if (Zend_Auth::getInstance()->hasIdentity()) { //save the owner
$sitesRecord->idOwner = Zend_Auth::getInstance()->getIdentity()->idOwner; //retrieve the owner
$sitesRecord->save();
} else {
throw new Exception("your session have expired: \n please login again");
}
}
}
/**
* return the calling subform
* #param type $post
* #return type
*/
public function getSubformByPost($post) {
$form = new Diff_Form_Download();
$form = $this->view->form;
$subform = new Diff_Form_DownloadSubform();
$subformName = "site" . $post['idSite'];
$subform = $form->getSubForm($subformName);
return $subform;
}
public function refreshOneDiff($post) {
$debugString;
if (is_array($post)) {
$form = new Diff_Form_Download();
$form = $this->view->form;
$subform = new Diff_Form_DownloadSubform();
$subform = $this->getSubformByPost($post);
if (!$subform)
$subform = $this->view->form->getSubformByPost('NewSite');
$url = $subform->getUrl();
$idSite = $subform->getIdSite();
$crawler = new Crawler();
$newpageContent = $crawler->get_web_page($url);
$siteRecord = new Diff_Model_Sites();
$siteRecord = $subform->getSiteRecord();
if ($siteRecord) //check if the record is not null
$oldpageContent = $siteRecord->get('content');
else
$oldpageContent = null;
$differences = $this->getDiff($oldpageContent, $newpageContent);
if (!is_null($differences)) {
$siteRecord->content = $newpageContent;
$subform->setContent($newpageContent);
$subform->setContentDiff($differences);
$subform->setSiteRecord($siteRecord);
$subform = $this->getSubformByPost($post);
$debugString = $subform->getContent();
}
//echo $debugString;
$sitePresence = Doctrine_Core::getTable('Diff_Model_Sites')->findOneBy('idSite', $idSite);
if ($sitePresence) {
//$this->saveSite($post);
$this->debugtry($post);
}
} else {
}
}
Basically what I'm doing here is:
1) grab a the form from the view
2) grab a subform from the form (let's call it SubformX)
3) grab an object "siteRecordX" from SubformX
4) change a value of "siteRecordX"
5) call a function saveRecord()
6) In this function regrab the same SubformX and echoing the value of the object siteRecordX
Surprisingly if i change a variable of SubformX it will stay that way, if I change a variable of an object of SubformX it will remain unchanged (if I retrieve SubformX).
It looks like, even if SubformX is passed by reference it is not the same for it's subobjects, wich are passed by value and so they disappear changing the context of the function.
Can you please help me?
Thanks
EDIT
I still cannot solve this issue nor understand it:
This is the constructor of the subform:
public function __construct($site = null, $options = null) {
if ($site instanceof Diff_Model_Sites) {
$this->_shortName = $site->get('shortName');
$this->_url = $site->get('url');
$this->_content = $site->get('content');
$this->_idSite = $site->get('idSite');
$this->_siteRecord = $site;
$this->_lastChanged = $site->get('lastChanged');
}parent::__construct($options);}
while this is the function of SubformX i use to set the value.
public function setContent($contentText) {
$this->_siteRecord->content = $contentText;
$this->_content = $contentText;
}
and this is the function of the subform that I call to get the value
public function getContent() {
if (isset($this->_siteRecord)) {
//return $this->_content;
return $this->_siteRecord->content;
}
}
with the commented line I'm able to retrieve the updated value, not with the second.
This is a real mystery to me because i set and get them exactly the same way at exactly the same point and i cannot understand the difference.
Your _siteRecord property is an ORM object (Doctrine, it appears). So its data may have some behaviors that are not standard for a reference-type object. It surely has some override of __get and __set. It also employs caching. These things are necessary to keep the database-model interaction working properly, but they can confuse what should be a reference and value types. (See: http://www.codinghorror.com/blog/2006/06/object-relational-mapping-is-the-vietnam-of-computer-science.html)
P.S.: in your constructor you use:
$this->_content = $site->get('content');
$this->_siteRecord = $site;
but in your getContent() you use:
$this->_siteRecord->content;
That difference might be part of the problem.
Thank you all guys. It was Doctrine caching.
I have not investigated further the problem, but after getting rid of Doctrine everything works fine.
I have lost one entire day after this issue.
Moreover today I have lost another day for another curious problem related to Doctrine.
It seems that each time you gather data from your db Doctrine decode them for you (just like the php function utf8_decode($data).
Of course if you get the data and then put it back in the db again it will result in a total mayhem of coding and decoding.
This is enough. I still think that ORM are great programming tools but simply Doctrine is not.
I will not rest in peace since I'll have it eliminated from my program.
I will use Zend_Db library instead. Which I have mostly already done without regret and without facing the above-mentioned Doctrine's problems.
Again thanks to Seth Battin and Dave Random for the help and patience to understand my noob-coding.
Right now I am displaying HTML in my view by using html_entity_decode:
<strong>Body:</strong>
<?php echo html_entity_decode($post->body); ?></p>
But is there another way to do in when I am passing data to my view, in:
public function action_view($id = null)
{
$data['post'] = Model_Post::find($id);
is_null($id) and Response::redirect('Post');
$this->template->title = "Post";
$this->template->content = View::forge('post/view', $data);
}
I read the documentation and tried:
public function action_view($id = null)
{
$data['post'] = Model_Post::find($id);
is_null($id) and Response::redirect('Post');
$this->template->title = "Post";
$this->template->content = View::forge('post/view', $data);
View::$auto_encode = false;
}
But this just gave me an "access to undeclared static property". Clearly I am doing something wrong...
As I can see you are not setting auto_encode correctly.
Try this and see if it's what you are looking for.
public function action_view($id = null)
{
$view = View::forge('post/view');
is_null($id) and Response::redirect('Post');
$post = Model_Post::find($id);
$view->set('post', $post, false); //Here the auto_encode is set to false
$this->template->title = "Post";
$this->template->content = $view;
}
Hope this helps
There are abunch of ways to do this:
protected $this->auto_encode = false;
That property in the controller will stop ALL assigned values from being encoded.
Otherwise, use this:
$this->template->set('title', "Post", false);
$this->template->set('content', $view, false);
That'll stop the specific value being encoded.