PHP MVC Framework Best Practice: How to distinguish model variables from other variables in view templates?

StackOverflow https://stackoverflow.com/questions/22162155

  •  19-10-2022
  •  | 
  •  

Question

Is there a best practice how to refer to/keep variables separate when writing view template files for PHP MVC/MVP frameworks, and how to avoid possible variable name conflicts?

Problematic View Template Code Snippet

<html>
  <head>
    <title>{{$title}}</title> <!-- page title wanted here -->
  </head>
  <body>
    <pre>
    Your Model Data
    Title: {{$title}} <!-- model field named 'title' wanted here -->
    Date: {{$date}}
    ...

As you can see, the $title variable is poorly named and could mean either the page title or the model title field. The same could easily happen with the $date variable.

In different past projects I have either employed a strategy of naming variables differently or placing them in a subarray when assigning them to the view or the function creating the view. (e.g. identifying variables pertaining the view only by prefixing them with view_ or putting them in an array named view[].)

Neither of this seems to be a very elegant for me and I would like know if others have had the same problem and came up with a better solution.

No correct solution

OTHER TIPS

It's fairly common to just send the entire model instance to the View, as opposed to sending the data in individual variables. This solves the name-conflict problems.

After all, if you need to output a collection of models in a View, you have to use the models directly anyway. So there's no reason why it'd be any different when sending one model to the view.

You can still format the data inside the model any way that you want and pass it to the View using the model as a data container. This also makes it easier to expand on the View's content in the future, since all the model's data will be available to you.

With Laravel, I'd do the following for an example blog post.

In my controller:

//get the post
$post = Post::find(1);
//set the page title
$title = $post->title . ' - Some other stuff I want to append';
//send them to the view
return View::make('blog.post')->with([
   'title' => $title,
   'post' => $post
]);

In my View:

....
<head><title>{{ $title }}</title</head>
<body>
<h1>{{ $post->title }}</h1>
<em>{{ $post->date }}</em>
{{ $post->content }}
</body>
...

With that, the model object is assigned to post and you can access access all model properties through the post object. This separates them from other variables. Very simple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top