I need to see all the variables that are available in a view. I am a front end developer so I mostly work in the views directory. I don't always know which variables are being passed to the templates by the back end dev. Instead of asking him every time an easy solution would be some type of snippet that I can temporarily paste into the view that I'm working on so I can see all the available variables and even better if I can also see their types and values.
I tried this:
<pre><?php var_dump(get_defined_vars()); ?></pre>
But since I am using Codeigniter it also shows all the other tons and tons of variables that are passed in by the framework.
I only want to display the variables that were passed specifically from the controller that loaded the view. Is there any way to do this?
var_dump($this->_ci_cached_vars);
One possibility could be to do something like this:
$data['user'] = $user;
$data['cart'] = $cart;
$data['data'] = $data;
$this->load->view('view', $data);
If you did something like this, then you could always access a data array that looked the same as before it was parsed for the view.
Then you could use something like print_r or whatever you wanted to take a look at the array.
Related
I use codeigniter with smarty.
I have a variable stored in the db called $serverName. I want to expand it to its actual value "Pedrosite". But when the page is loaded, it displays exactly {$serverName} and not the value.
So I found this solution on stackoverflow, using smarty's fetch function:
$data['content'] contains the text from the database.
$data['content'] = $this->CI->smarty->fetch('string:'.$data['content']);
With that, I can display the smarty vars, like: {$smarty.const.FCPATH}
But none of my custom $vars while they can be shown in a regular template (.tpl).
So I found this workaround that looks very hacky to me:
$this->CI->smarty->assign('serverName', $this->CI->config->item('server_name'));
I can put this in one of my __construct function and then it will affect the whole site, and then it loads properly. But I'm not sure it's the right way to proceed at all.
I don't really understand your question, but, if you have your variable $serverName and it content "Pedrosite" you can display it like that :
$this->smarty->assign('serverName' , $serverName);
$this->smarty->view('/modules/xxxxxx');
And display it in your .html file for example :
<p>{$serverName}</p>
I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example:
A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpage so I know how to travel through $result from my View.
A form POST a $request to a Controller, I use pr($request) to see what is sending in before processing it in the Controller. The content of $request will be displayed immediately on the webpage right after I hit Submit the form.
I'm wondering if I could do the same thing in django instead of going to the shell and try pprint (or could I just use pprint to print out to the web???)
This is a really simple example about what I'm talking about:
app_name/views.py:
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
return render(request, 'socs/detail.html', {'soc': soc})
How can I just view clearly what is in "soc". In cakephp, I could just pr($soc) right there and it will be displayed right on the detail.html page.
I have tried this and it didn't work (I'm sure it's basic but i'm just new to this)
import pprint
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
pprint.pprint(soc)
return render(request, 'socs/detail.html', {'soc': soc})
I have spent two days doing research but I couldn't find the answer. I'm hoping one of you can help this newbie out.
The way you're trying to print will show the print in the terminal that is running your Django server. If you just need to see it quick, check there.
If you want to output the value on to the rendered page, you'll have to include it in the template using template tages. It looks like you send {'soc': soc} to your template as context. Because of this, you should be able to use it in your template. So, in your template (socs/detail.html), just add {{ soc }} somewhere and it should print out the value. The template has full access to the object, so if you wanted something specific, you can also print that instead (like {{ soc.id }}).
If you want to see everything that's in the object without specifying all of the different fields yourself, send OBJECT.__dir__. For example, for this you'd send {'soc': soc.__dir__} as your context. Keep in mind that this likely should not be used for anything but inspection on your part.
If you'd like to learn more about Django's templating, check out the syntax and more.
Im looking for an elegant way to hand over data/params when using $f3->reroute();
I have multiple routes configured in a routes.ini:
GET #sso: /sso/first [sync] = Controller\Ccp\Sso->first, 0
GET #map: /map [sync] = Controller\MapController->second, 3600
Now I reroute(); to #map route, from first();
class Sso {
public function first($f3){
$msg = 'My message!';
if( !empty($msg) ){
$f3->reroute('#map');
}
}
}
Is there any "elegant" way to pass data (e.g. $msg) right into $MapController->second(); ?
I donĀ“t want to use $SESSION or the global $f->set('msg', $msg); for this.
This isn't an issue specific to fat-free-framework, but web in general. When you reroute, you tell the browser to redirect the user's browser page using a 303 header redirect code.
Take a minute to read the doc regarding re-routing: http://fatfreeframework.com/routing-engine#rerouting
There seems to be some contradicting information in your question, which leads me to question the purpose of what you are trying to achieve.
If you are rerouting, you can either use the session, cookies, or use part of the url to pass messages or references to a message.
If you do not need to redirect, but just want to call the function without changing the passed parameters, you could abstract the content of the function and call that function from both routes. You could also use the $f3 globals, which are a great way of passing data between functions in cases where you don't want to pass the data using the function call. is there a reason why you don't want to to use this? The data is global for the single session, so there is no security concern, and the data gets wiped at the end of the request, so there is very little extra footprint or effect on the server.
If you're alright with not using #map_name in re-routes you can do something like this:
$f3->reroute('path/?foo=bar');
Not the prettiest I'll admit. I wish $f3->reroute('#path_name?foo=bar') would work.
I'm new to MVC and I'm trying to understand how MVC fits in to what I'm used to.
Let's say I have a simple static website with the pages: Home, About, Contact.
And let's say that I have one xhtml/css "template" which will be the view for the whole site. To keep it simple, in that tag I'll have a variable for the page contents.
So in the controller am I supposed to have an individual function for the content for each page????
For example:.
function home()
{
$data['content'] = "<p>some html home page content</p>";
$this->load->view('myView', $data);
}
function about()
{
$data['content'] = "<p>some html about page content</p>";
$this->load->view('myView', $data);
}
So while I know this is a super-simplified look, is the best practice to create a function for each different page?
But what if you have a site with 100 pages? Doesn't the controller get too big to manage?
But then again, if you had a single controller for each page, that also seems that it would be tough to manage?
I am beginning to understand how the MVC concept is helpful for database connection tasks as well as some CRUD as well. But I remain confused as how to think about "pages" in MVC.
Any advice is much appreciated.
What's the best practice?
You don't have to have a function for each page.
a quick example I've found is:
<?php
//This is an example of a KISSMVC controller
//It is simply a function, which will be called by an URL such as:
//http://example.com/article/show/234
//TIP: Please assign default values to all parameters
function _show($articleid=0) {
//SECTION 1: INPUTS
//Filter, sanitize and store all inputs used by this controller
$articleid=min(0,(int)$articleid); //zero or positive integer
$uid = isset($_SESSION['authuid']) ? $_SESSION['authuid'] : 0;
$someconfig = $GLOBALS['registry']['someconfig'];
//SECTION 2: LOGIC
//Call functions/objects that implement your business logic with the inputs from SECTION 1
//Data returned from your Model should not contain UI specifics (such as html code)
$loggedinuser = new User();
$loggedinuser->retrieve($uid);
$article = new Article();
$article->retrieve($articleid);
//SECTION 3: PRESENTATION
//Call the view templates with the data obtained from SECTION 2
//A change in UI should only affect code in this section
//Sometimes there is no output needed, only a header redirect is returned
if (!$loggedinuser->hasPermission('view_article')) {
$vars['body']='<p class="error">You have no permission to access this page!</p>';
View::do_dump(APP_PATH.'views/mainlayout.php',$vars);
exit;
}
$vars['article']=$article;
//article template is defined in views/layout/view_article.php
$vars['body']=View::do_fetch('layouts/view_article.php',$vars);
View::do_dump(APP_PATH.'views/mainlayout.php',$vars);
}
Taken from http://kissmvc.com/php_mvc_framework/code
Which is a PHP implementation of MVC (its seemed to me like you're working with PHP).
You might want to have a look at their implementation etc. It was just the first one I found. Hope this helps.
The controller in MVC tends to be the biggest part of your code base. So as far as worrying about it getting too big, that's to be expected.
However, when using MVC, you typically want the Model-View-Controller to be a 1 to 1 relationship. If you have an about page, you'll want a controller specifically for that view and the actions associated with what you can do on that page. The response may be to load another view, in which case another controller will respond to events to that. The model can be shared amongst the controller's, but you don't want any parts of your view to know anything about your model or it'll break MVC, the controller being the piece that functions as the glue.
If you are indeed doing something with PHP as dtroy mentioned, that'll probably help out. Unfortunately, I'm coming from experience with MVC on the iPhone. Same concept though all around.
In summary though:
If you keep the controller responsible solely for the actions that can occur on a given view, like button clicks, etc... it should help keep your controller from getting too large and unwieldy.
Edit:
I forgot to mention, in response to your concern which I didn't address. To help with, for instance, "Controller Explosion", you may not necessarily want to create a controller for each page, but one for each type of view. For example, you may have a AboutViewController and a ContentViewController, and maybe a loginViewController. The AboutView and LoginView would be pretty unique, but if you can reuse your contentView. So if someone requested something about "Widgets", your content view would simply display information about widgets that it retrieved from your model, and display it in the appropriate location defined by your view. then when the user requests something about "gears", you can reuse the same ContentViewController to display different different information in the same fashion.
Basically you'll have a Page controller for your Page model. Then each page that you create will have a url like "/Pages/1", which will get routed to the "show" action of your Page controller.
MVC certainly takes a bit of getting used to, but once you get the hang of it, you'll really like it. Also check out resources on REST design, which will really help with problems like this.
When I design websites now, I think in terms of resources (models, more or less). So for instance, you will have many pages or users or questions or recipes or... each of these things is a thing/model. I usually make a separate controller for each one and put 7 actions in that controller:
index - used to show a list of all the Pages (URL like "/Pages")
show - used to show an individual Page (URL like "/Pages/1")
new - used to show a form to create a new Page
edit - used to show an edit form for a Page
create - used to actually create the new Page from the new form
update - used to actually update the Page from the edit form
destroy - used to delete a Page
This isn't for everyone (I don't want to turn this into a REST debate), but it helps me a lot, and I think it makes sense when you're dealing with things that are clearly objects like Pages.
The controllers contain the empty functions if there are no actions on the page. You don't have to pass page content via controller.
Place all the content to 'view' component of current unit.
If you have a site with 100 pages, you would want most of your content to be stored in a database.
your URLs would be altered to look something like this:
http://yoursite.com/showpage?pageid=mvc
http://yoursite.com/showpage?pageid=home
http://yoursite.com/showpage?pageid=whatever
and your controller would look something like this:
function showpage()
{
$post = yourframework.getmodel('post').getPost($_GET['pageid']);
$data['title'] = "<p>" . $post.title . "</p>";
$data['content'] = "<p>" . $post.title . "</p>";
$this->load->view('myView', $data);
}
Not syntactically correct but you get the idea. You need to have only one function which delivers all 100 of your pages. This would work if all your pages have a similar structure.
In other words, mvc works just like vanilla php... (but hopefully looks a bit cleaner)
I have made a tiny ModX snippet that looks like this
<?php
$theMenu = $modx->runSnippet('Wayfinder',
array("startId" => 0, "level"=>1)
);
echo $theMenu;
?>
but I would like it to pass ALL params it receives to Wayfinder. I will only be modifying the "level" parameter from my snippet.
Is there any way, without naming all the relevant variables individually, to cycle through all the currently SET variables in PHP?
Edit: I don't think that get_defined_vars is the right way to go, as it gets too much stuff. This trivial PHP page prints out the number 14, for instance:
<?php
echo count(get_defined_vars());
?>
This might be useful: get_defined_vars() ?
Edit
From http://bobsguides.com/modx-snippet-faq.html:
You can also access the parameters via
the associative array
$modx->event->params.
try using foreach to auto assign parameters to wayfinder object