I am trying to roll my own MVC purely for learning purposes, but am hitting a snag when I try to load in the view files. Here's my problem:
Front controller grabs appropriate page controller, page controller include_once() the appropriate view. The view is a file containing HTML and PHP. When I return the include file from the controller, the included file content appear out of sequence of the PAGE layout intended. (example: I want to display HEADER CONTENT FOOTER, but when I include the view's contents, my controller spits out CONTENT, HEADER, 1, FOOTER).
In my front controller I am attempting to set my included file contents to a variable I then echo in between my HEAD and FOOTER in the PAGE template. But this does not work as intended. I can wrap my view file contents in: return "code" but I don't want the added headache of worrying about stray quotes/double quotes in my view code that could break the script. I have tried file_get_contents(), but this only spits out a string (albeit in the right place/sequence in my template) and does not the PHP in my view files correctly (ie at all).
My question is: Is there a way I can return my view file to my front controller using include_once() in a variable? I can't seem to find a adequate answer to this. I'd be happy to add my code if it would help.
You can assign a return value from an include(). A lesser-known feature of this function is that you can have a file like this:
<?php
// config.php
return array('database_host' => 'localhost');
and you can read it in thus:
<?php
$config = include('config.php');
However, you're wanting to do this:
<!-- text.html -->
<h1>Heading</h1>
<p>Hello</p>
and read it in with this:
$html = include('text.html);
You can try doing that, but as soon as the include() scans the file, the output will be sent to the web server. That's how PHP works. Since there is no explicit return value, moreover, the $html variable comes back empty.
Thus, we use the output buffering functions to modify PHP's behaviour: we start buffering, and then we fetch it and clear it. This is then not sent to Apache, unless of course you choose to turn off output buffering and echo what you have collected, in which case it goes back into the normal output buffer and is actually sent.
Related
for my website i have some static header/footer HTML and some dynamic content generated by PHP. When it comes to render the output I just include a file with HTML inside from my PHP code. This works perfect - also when I switch between pages.
<?php
...
public function render() {
...
// file for output
include $fileName;
...
}
?>
But I also need some header.hmtl and footer.html that contains the static information (text and some divs for formating) and want to put that in front of each dynamic content, represented by $fileName.
So I simply add two includes that represent the static information.
// file for output
include "./Views/html/header.html";
include $fileName;
include "./Views/html/footer.html";
So this does what I like (formatting, etc.), but if I switch from page to page it flickers for one time. As much as I can see the page is first renderd without header/footer information and then a second time with header/footer information. Looks like this generates the flickering.
How can I avoid this ? Is this probable related to a RewriteRule of my MVC-Framework ?
Any hint is appreciated.
thanks to Lawrence who led me to the right term. It solved my problem completely.
I put a <body><script>0</script><!-- rest of the code --></body> in my code and it works now. –
I'm attempting to make a template file for a CMS that I'm making where the template file can contain variables like {username} as regular text that get replaced when the page gets included on the index.php page.
Example:
Index Page:
<?php include('templates/123/index.php'); ?>
templates/123/index.php page
<?php include('header.php'); ?>
Welcome {username}
<?php include('footer.php'); ?>
I've tried several methods; however, always run into problems because the page I'm trying to change the content on includes PHP code. Every method I try either 1) messes up because the opening and closing of PHP tags within the document OR 2) just echoes out the PHP code in the document. Is there any way that I can still achieve this? Maybe even with a class of some kind? I just want to be able to achieve this safely.
I will also be using this to where custom variables like {content1} get replaces with a php code that will be ioncubed that retrieves the data from database for content located in column1, same with {column2} {column3} and {column4}. I'm just trying to make the creation of templates extremely easy. (so I'd like to make the code work for that as well)
My preferred method of doing stuff like this involves starting my code with:
ob_start(function($c) {
$replacements = array(
"username"=>"Kolink",
"rank"=>"Awesome"
);
return preg_replace_callback("/{(\w+)}/",function($m) use ($replacements) {
return isset($replacements[$m[1]]) ? $replacements[$m[1]] : $m[0];
},$c);
});
Two steps I suggest
Load the result of your file "templates/123/index.php" into a variable. see this link for how to do it assign output of execution of PHP script to a variable?
use strtr() function to replace your placeholder i.e {username} with actual values
I think this will server your needs.
So I would have a template file called template.php and inside, it would have:
<html>
some other content
<?php $name ?>
</html>
Essentially, I want to pull the name from the database and insert it into $name and save that entire page as a new file.
So let say in the database, I had a name called Joe, the new file I create would have the following content inside:
<html>
some other content
Joe
</html>
The only issue I am having is finding the right functions to actually replace the variable from the template file, and being able to save it into a new file.
That's not how templates usually work. You should have a template file, substitute variables for their values, and display it to the user. You can cache these generated templates (the ones that are always the same) but you never make a new template file for each user and save it permanently. That makes managing and updating the application way more difficult than you want.
I recommend using a simple template system like RainTPL. That's what I use for most of my projects... it's very simple to use and provides all the basic functionality you would need.
You can also use just PHP for this... there are a few answers on SO that cover this so I won't get into it.
Using PHP as template engine
Using Template on PHP
Look at the answer I gave to this question a while back. There I explain how "variable parsing" usually works.
When I create a template loader I generally use output buffering with php include. This allows you to run the page as a php file without displaying its content before you are ready. The advantage to "parsing" your php files this way is that you can still run loops and functions.
Here's an example of how to use output buffering with PHP to create what you're wanting.
The Template template.php
<html>
some other content
<?php $name ?>
</html>
Where your database code and stuff is index.php
<?php
$name = 'John Doe';
if( /* some sort of caching system */ ) {
$parsed_template = file_get_contents('parsed_template.html');
}else {
ob_start();
include 'template.php';
$parsed_template = ob_get_clean();
file_put_contents('parsed_template.html', $parsed_template);
}
echo $parsed_template;
?>
I've created my own templating/viewing engine to use with Codeigniter. In it I'm able to specify certain css/js files to use with a specific view. I assign the file names in an array, which will then get looped through while echoing the necessary <link href="X"..., <script type="X"..., etc for the respective file type in the header file of the template.
The problem is that I can't seem to use the resources I'm trying to include. The CSS/JS files aren't working even though they're being included and embedded and everything looks right in terms of the syntax in the HTML source code.
My theory is that because I'm using echo to actually print the link/script object into the HTML, that it's actually not really an object that HTML can recognize? Kind of like trying to echo an object in PHP - it doesnt work.
Any advise?
It does not matter if you use plain HTML of php generated code. For the browser it is all the same.
You need to check your source code, and check if the scripts you include are accessible. So copy/paste the src="blabla" from your source code from your browser, and paste it in the address-bar and see what happens.
It is definitely not PHP's fault.
I want to use php to easily maintain my website, but I simply can't figure out the language - I've found some tuts online, and some other questions here, but none help me.
I've divided my site into some .php files, header/footer and such - And using
works fine..
Now I want the content of my site, to update according to which menu I click on at my site.
http://dawtano.com/pp/
If I click on "about" I want the "Hello World" to open inside my content div, but I can't get the right php code to do it.
I think you should do this---
Note: This will only work if the CSS styling are on the current directory! ()
<div>
<?php
$html_page = implode('', file('http://dawtano.com/pp/'));
echo $html;
?>
</div>
Hope this helps!
well currently your links are taking you to a separate page entirely. So why not just code it so that your include file is specific to the page. i.e, on about.php, use something like
include 'about_content.php
in your contetnt div.
If you're looking for your content to load dynamically into the content div you'll need to look into using ajax to fetch the content pages.
One popular way to construct the site is to have a single php script which displays content based upon a $_GET variable like 'page' or 'content', and then make the link as:
'http://dawtano.com/pp/index.php?page=helloworldcontent'
Using this method, you would need to check if the variable ($_GET['page']) is set using isset(), and then make sure the string is safe... as anybody with a browser could just type in some mumbo-magic script and hijack your site:
'http://dawtano.com/pp/index.php?page=somecleaverlycraftedhax'
Once it exists and is safe, add the '.php' to the file name and include that file... if it exists! If it doesn't exist, then you will need some code to handle that, probably by displaying a 'File not Found' message, or redirecting home, or something.
I prefer not to do this because it is a pain to make safe, and I feel like it is pretty ugly. What I do instead is put all the header/footer/navbar/title bar scripts into seperate 'display' functions, and put them in another file.
Then include this file with the function definitions, and call all the 'display' functions to set up the page. So every php script in your site might look like:
<?php
include 'html_display_functions.php';
/* put lines here to parse $_GET and $_POST, session_start()/$_SESSION, etc... */
print_html_pre_content();
print '<p>Hello, world!</p>';
print_html_post_content();
?>
Since every script will have this structure, you can just create a template file once. When you want to create a new page for your site, copy the template, rename the copy to the php filename you want, and add content between the two print functions.
You also keep the ability to modify the header/footer/navbar/title bar for the whole site in a central location, namely the included file with the functions.
You might be looking for some sort of Template Engine which allows you to create your pages out of variable parts. You could have a look at TBS, which is more or less what is suggested by the name. But there is a whole lot more engines out there which could do the job.
If that's already too much over the top, maybe Apache SSI (Server Side Includes) are a try for you.
A little suggestion from my side, I am often using Apaches mod_rewrite in connection with a single controller.php file. Apaches mod_rewrite will then send all request to the controller.php which will fetch the appropriate page parts for the requested page using TBS and return the respective page. So you have the controll of the page in one location only.
To your original question about.php could look like:
<?php
include('header.php');
?>
// original page content as html for about.php
// assuming header ends with the starting div <div> where you like the content to appear
// and footer starts with the closing div </div>
// if you need variable content here, simply use <?php echo $your_variable ?>
<?php
include('footer.php');
?>
The best way would be to use a switch statement:
http://php.net/manual/en/control-structures.switch.php
Something like this:
<?php
include("header.php");
$page = $_GET['page'];
switch($page)
{
case "about":
include "about.php";
break;
case "faq":
include "faq.php";
break;
case "help":
include "help.php";
break;
default:
include "home.php";
}
include("footer.php);
?>
Then just make all of your links look like this:
http://www.example.com/index.php?page=home
Just replace home with the correct page.