Is this acceptable to be placed in a view? - php

Kohana (and probably other frameworks) allow you get a route and echo its URL, creating routes that are easy to maintain.
Contact
Is this OK to have in the view, or should I assign it to a variable, and then pass the view the variable?
Thanks

You aren't performing logic here. This is perfectly acceptable.
Of course your view code would be a bit cleaner if you created a variable in your controller, but this really is fine IMHO.

I find such a concatenation unnecessary. It seems url::base() going to be used in every link on the site. Why not to have a method to add it automatically? Something like Route::url("contact")
And usage of such a construct in the template is OK.

You can create a function or static method for generating urls:
public static function url($routename, array $params = NULL)
{
return url::base().Route::get($routename)->uri($params);
}

Related

Get parameter passed in URL in Laravel view as variable directly?

Right now, if I have a parameter in a URL in one of my Laravel projects, I have to detect the route and grab the parameter:
Route::get('mission/{name}', 'MissionsController#show');
Pass the $name parameter as an argument to my controller:
class MissionsController extends BaseController {
public function show($missionName) {
...
}
}
Then pass it along to the view that is returned in my controller method:
return View::make('missions.mission', array(
'name' => $missionName
));
Before then using the $missionName variable in my view:
<p>{{ $missionName }}</p>
This is quite a roundabout way of doing so. Is there any way I can get the parameter from the URL directly in my view? I've tried accessing the $_GET superglobal, but it is empty. Surely there must be a better way of doing this.
Thoughts?
Use this code :
{{ Route::current()->getParameter('theParameterName') }}
EDIT: Above doesn't seem to be supported anymore in recent Laravel versions. You should use #lukasgeiter answer instead:
Route::input('name');
There is a nice shortcut for Route::current()->getParameter():
Route::input('name');
For small projects or simple examples, it may seem like this is a "roundabout" way, however this is the way it should be. In order to create more reusable, quality code, you need to have this separation of concerns. An over-simplified idea follows.
It is your route's job to figure out which controller needs to be called, and to make sure it is called with the correct parameters.
It is your controller's job to read the state of the application (input), communicate with the model (if needed), send the data into the view, and return the response. There's plenty opinion on whether or not this violates the Single Responsibility Principle, but no need to go into that here.
It is the view's job to use the data passed to it to build the response. The view shouldn't care where the data came from or how it was gotten, only that it now has it and can do what it needs. Your $missionName should be able to come from a URL segment, a URL request variable, a field on a model, or any other place you can think of, but the view shouldn't know any of that.

How to simulate a request from view.

I'm new in cakephp and I'm just wondering, how to test models and controllers without using views?
I have to simulate saving data using models and controllers without using froms from views. I was thinking about to make an array with the needed values, but maybe there is a better way to do that?
you can mock your model functions using code like:
$model = $this->getMockForModel('MyModel', array('save'));
$model->expects($this->once())
->method('save')
->will($this->returnValue(true));
You can output variables at any time from controllers (or models) without getting to the views. Yes, it's not how you should do things with an MVC framework, but for testing, it's pretty easy to whack this below your database call in the model/controller:
<? echo '<pre>'; print_r($my_array); exit; ?>
The other thing you can do is at the top of your action function in the controller put:
$this->layout = '';
$this->render(false);
... which will bypass the layout and skip the view rendering, so you can output whatever you like within that function without using the view.
At the beginning of your action, you may use:
$this->autoRender = false;
This will allow you to access your action directly by going to it's path (e.g. CONTROLLER/ACTION). Before passing your data array to save() or saveAll(), I recommend double-checking it with Debugger::dump(), and follow that with die(). This will make the array containing the save data print on your screen so you can verify it looks proper and follows Cake's conventions. The die() will prevent it from actually saving the data.
If everything looks correct, remove the dump() and die() and test it out again.
The first response, from Ayo Akinyemi, should also work well if you are Unit Testing your application.

CodeIgniter custom function

To check If a user is logged in I need to pull off a pretty long if-statement and then redirect the user depending if the user is logged in or not. I think a custom function like
if (logged_in()) { redirect }
Would be more appropriative. But building a library for one function seems unnecessary to me. What should I do?
I need to pull off a pretty long if-statement, but building a library for one function seems unnecessary
It's not at all "unnecessary", neither is it strictly "necessary", but it's probably a good idea to create a library/class for this.
If you have a lot of logic you need to work with, "a pretty long if-statement" for example, using a class can help you break this down into smaller pieces and make the logic more manageable. If you only need to call one public method of the class, like $this->auth->is_logged_in(), there's nothing wrong with that, then you can create a small helper file or wrapper function to call the method, and put the redirect logic there instead of the class. Something like this perhaps:
// Make sure your "auth" library is autoloaded or load it here
function logged_in($redirect = TRUE)
{
$CI =& get_instance();
$logged_in = $CI->auth->is_logged_in();
// Redirect the user...
if ( ! $logged_in AND $redirect)
{
redirect('somewhere/else/');
}
// Or just check if they are logged in
return $logged_in;
}
Using a class/library has many benefits, and with something as complicated as user authorization you will benefit greatly from taking advantage of it, especially once your project starts to expand and you need more utility.
Although helpers are usually preserved for decoupled functions that have nothing to do with your app, I think in this case they are appropriate. Simply create a helper function called is_logged_in.
To learn more about helpers, visit the Docs:
http://codeigniter.com/user_guide/general/helpers.html

simple cakephp problem

I know this is a really simple thing that I really should know but I'm trying to learn cakephp without having done much php before. I've been told thats a stupid idea, but I'm doing it for fun and so I'm doing it.
I want to pass an array from one controller action to another controllers action and then pass it to the view. I have:
sponges_controller.php
$info = $this->data;
$this->redirect(array('controller'=>'baths', 'action'=>'dashboard', $info));
baths_controller.php
function dashboard($info) {
$this->set('info', $info);
}
and then
<?php echo debug($info); ?>
in the view for dashboard.
I've tried various ways but can't make it work. All it does is print out Array()
Plz help me! :) Julia
You can't pass data that way from one controller to the other as far as I know, at most you can concat a string to the action, like an ID for view or editing.
If you want to pass the info you could try setting it in the SESSION variable in the following way:
$this->Session->write('Info', $info);
And in your other controller you can check for it:
$this->Session->read('Info');
It looks like cake will not let you pass an array into a controller action. I set up a simple example and I got an 'array to string conversion error'. Is there a specific reason why you aren't just posting the data to baths/dashboard? I can think of a workaround for your problem, but it is quite messy.
8vius's solution above will definitely work.
Here is another way, but using sessions is probably a lot better
$str = http_build_query($info);
$this->redirect('/baths/dashboard?'.$str);
So then in your baths/dashboard action, you will have access to your data using the php $_GET array.
So if you originally had this->data['name'] you can access it with $_GET['name']
I'm not sure about the passing data in different controllers but within the same controller we can do it just like a function call by writing something like this.
$this->function_name($info);
This will perfectly work as intended. I've not tried this type of data passing in different controllers function.

How do I pass information my a controller to a view in PHP (no framework)?

Using PHP, If I have a model (a class) where I various queries, whatever I need, and in my controller, I use myModel = new CustomerModel(); and later in the controller, say I call myMyodel in the controller (I know looks like codeigniter but I am not using a framework) to:
$data['query'] = myModel.OrderByLastName();
how do I pass that $data['query'] to a view, a separate .php page?
I don't wan to echo anything from my controller.
Also, was hoping this design, the way I explained it makes sense. Or am I wasting time with the model class?
Typically, you'd instantiate a view object:
$view = new View();
Pass it the info it needs():
$view->set($name1, $value1);
$view->set($name2, $value2);
...
Then invoke the view's renderer:
$view->render();
The way Django works is the controller basically renders a template using a templating system. It passes the data in Contexts, like this:
data['query'] = myModel.OrderByLastName();
context = {'data': data['query']}
page = loader.get_template('folder/template.phtml')
return render_to_page(page, context)
roughly.
Obviously, you're writing your own system so you've got some room on exactly how you implement it. I don't know if that's exactly what you want, but it might give you a workable idea.

Categories