CMS permalink and templating system how to? - php

I want to understand how to use templating system and permalinks on php websites :D !..
let me describe my self more,
1.currently i have 20 files each have its own php logic (index.php,wizard.php,search.php etc)
ALL use same class's and includes.(install.php include all the required for all class's in my project abd u require_once(install.php) in all files)
i wana remodel my website into.
Analyze URL requested ---> IDENTIFY requested page ---> GET TEMPLATE for THIS PAGE -->MODIFY header(meta) and footer(javascript) ---> add logic ---> display page :D.
can some one put me on right learning track :D !. cuz i hv coded my website fully in oop and made all its content loads dynamically from MYSQL (simple small CMS) but i have no clue how to join template and php into index without repeating my self and create different file for each page in my web ! (each file do different jobs of course like file users.php does login and registration and userprofile etc)
Hope my english wassnt too too bad and u could understand my question :D !
My current approach so far:
Mysql table : page_tbl
columns: pagename,LogicFile,templateFile,MetaTag.
index.php?pagename
will check if not already cached or not listed for chacing it will :
Mysql:SELECT * WHERE pagename='$_GET['page']'
loginfiles = cars.php,search.php (will be exploded with , and included)
Template files = will be also exploded and modified according to MetaTag.
Metatag: Serialized assoc array with ['name']=['value'];
Then i start buffer output , replace template with new descriptions and keywords(auto generated)
include logic files
include footer.php (which include the scripts)
am i near to correct rout or still far away ? or am did i lose my track and over killing

If you are unsure whether you want to write your own, or use an existing one.
It is going to be a quite possibly very rewarding experience but a very time consuming one to write your own.
If you have a task at hand that you need to be solved, use an existing one.
That being said there are plenty of templating systems, smarty being the most long-lived one. You can find a short discussion on 5 popular ones at phpbuilder.
You also have entire Frameworks that you might want to consider. They are more than just a templating system, where database stuff, ajax helpers etc are included. Zend, CakePHP, and Codeigniter being popular ones. You can find comparisons of these at phpframeworks.

The best way is to take this route:
parse request data
determine controller which will be used
in controller select layout and template [layout "includes" template, it hold the contents that are common to all pages and template has the request-specific content]
in controller also fetch the data from database [MVP way]
assign data to array and pass it to the layout, it'll pass the data futher to the template
in layout and template use data from that array and construct view
pass everything to the browser
This is the way the frameworks work, and it isn't that bad. ;]

Related

CakePHP Dynamically Add new Forms (WYSIWYG)

I've been asked to create a CakePHP plugin that would allow users to dynamically generate forms. This doesn't sound too hard in and of itself (pull fields from DB, figure out what kind of input, show in HTML), but I don't understand how I can "save" the forms to a new page.
From my understanding, Wordpress circumvents this problem by storing all data in the database, and can use shortcodes to just "insert" the form into another page. Seeing that CakePHP handles relies on CTP files to define views (and not Database fields), I don't see any simple approach to doing this.
Is this goal of a WYSIWYG form editor possible in CakePHP (without having to resort to terrible practices like editing CTP/PHP files from within the app)? If so, can you point me towards some strategies I can use to develop this plugin?
I'm not sure what you do with the dynamic form, to me it sounds like you're describing two totally different things.
Save the structure of the generated form somehow in the DB, key/value, serialized via php or as json object
Return the data, set it to the view
Write a helper that turns the structure that describes the form again in
The editable version, restore the form
Parses the structure and returns the HTML of whatever the fields of the form should do
You'll have to write your own parser that looks for things like [gallery id=1] and replace that with the result of a function call. Assuming that this is what you want to do. So you'll have to map the "gallery" to a functional call. I think the best here would be to use requestAction()
The *.ctp files are what WP considers it's template files, and honestly, Wordpress is just a horrible awkward piece of software from a developer perspective.

php dynamically create new pages in custom cms

I'm creating my own CMS from scratch as a way to build my php and mysql skills. Everything is going well, but I'm at the point where I want to create individual post pages for each blog post I write. So the index.php page has a list of all my blogs with snippets of each post and there is a read more button that should take the user to the full page for each blog post. Each post has a url created from the blog title entered in the "create post" form. I'm trying to figure out how to create unique pages for each post without passing the title, subhead, post content and other info through the GET.
This also dovetails with another feature I'm trying to add. I want to be able to create individual pages using a "create page" form like I did for my posts. So if I want an "about us" page I go to my admin form, fill out the title, add the content, and when I hit submit it creates the page dynamically. I have thought all day about how I'd do these two things but can't quite figure out how I can do this.
FYI, I'm not asking for code, I just need a push in the right direction as I try to conceptualize how to achieve this. Thanks!
If you're not familiar with the Model-View-Controller pattern, reading up on it might be prudent. MVC is frequently the right starting place for high-level design of web applications.
Also, a CMS is a big enough project you should consider using a PHP framework like CodeIgniter, Symfony, Zend, etc. to make your life easier. It removes a lot of the drudge work and common tasks.
Dynamic Page Creation and Display
I think you want to split it into two things: the text content (basically what you put in the forms) and the HTML templating surrounding that content.
When you make a page or blog post, you would want to store the actual content (what you type into the creation form) in a database of some sort (not necessarily an RDBMS, but if you're trying to build MySQL skills it's a reasonable choice).
Then you would use a separate function to bind that content into an HTML template and present it to the user when they load a given page.
URL Routing
To get nicer-looking URLs you can use something like apache's mod_rewrite. You can use that to convert a URL like this:
posts/how-to-make-a-cms
to this:
posts.php?title=how-to-make-a-cms
Then you can have posts.php read from GET as normal. How you choose to do the conversion is pretty open-ended.
To avoid getting really complicated rewrites, people often just structure everything to go to a central routing script which figures out what class and method to call and what arguments to pass it. So it would rewrite the URL above to:
main.php?a=posts/how-to-make-a-cms
Then main.php would parse out the segments of that argument from GET and figure out where to send them. Like it might take posts/show/how-to-make-a-cms and do something like:
$o = new Posts();
$o->show("how-to-make-a-cms");
If you do it that way, I think you can avoid mod_rewrite entirely as long as you're willing to accept only slightly pretty URLs, like this:
mysite.com/main.php?/posts/show/how-to-make-a-cms
I haven't done this type of thing before (because the frameworks do it so beautifully already), so I might be missing some minor details.
You should watch some tutorials from phpacademy.org or thenewboston.org, they have best and most valuable tutorials ever made about PHP.
I think you may try to start from that course/playlist:
phpacademy.org: PHP Tutorials: Creating a Blog
If you don't understand everything, watch this:
thenewboston.org: Official Beginner PHP Tutorials Playlist!
If you have no problems with PHP itself you may try to use some simple framework with MVC support. That helps A LOT in variable handling between pages, makes work with database easier etc.
phpacademy.org: Introduction to CodeIgniter
phpacademy.org: Introduction to CodeIgniter - Basic Website
I had the same problem. You can easily do this by using the fopen function. Here is a link to a tutorial: http://www.tizag.com/phpT/filecreate.php
<?php
function wwwcopy($link,$file)
{
$fp = #fopen($link,"r");
while(!feof($fp))
{
$cont.= fread($fp,1024);
}
fclose($fp);
$fp2 = #fopen($file,"w");
fwrite($fp2,$cont);
fclose($fp2);
}
//Example on using this function
wwwcopy("http://www.domain.com/list.php?member=sample", "sample.html");
//Another example
wwwcopy("http://www.domain.com/list.php?member=sample2", "sample2.html");
?>

Bespoke PHP Templating Engine

As a small part of a university project I'm working on (custom MVC based project management system), I need to develop a template engine. I don't wish to use an off the self system such as Smarty because I've written every other part of the project myself and don't want to go back on that now.
Anyway, I've managed to code something simple so far, I have a class, create an instance of it, add some data to the instance, then pass in a template file. The file has a series of tags like {this} when then get replaced with the data. Simple.
The issue I'm having is when it comes to looping things - i.e. a table of users or a list of categories. At the moment I have a template file for the page (users.html) which contains the opening and closing tags, with a template tag between them called {users}. I then have another template file (users-detail.html) which displays a table row with the user info in. I'm creating a new instance of the users-detail.html template, adding the data, parsing it, then placing the output (string of HTML) into an array. I then loop this array, attach all the strings together, then assign this to the {users} tag in the users.html template file.
As you can probably tell from that explanation it is a bit of a bodge, and there are probably better methods out there for doing what I'm trying to achieve. Ideally I want to avoid using PHP in the template files if possible, and I often need to have multiple loops within one template file.
If anyone has any tips / advice on how I can achieve this, or any tutorials I could follow to get some inspiration that would be much appreciated.
Thanks in advance.
I've seen that approach before (including another template for the insides of loops). I used to work on an old version of vbulletin which does (or did) this. It makes things annoyingly complicated because you can't just add a loop to a template - without setting up a whole new template for each layer of looping.
I'd advise you instead to go along the route of Smarty.
Classically, this statement:
I don't wish to use an off the self system such as Smarty because I've written every other part of the project myself and don't want to go back on that now.
... indicates you really should just be using Smarty. In the real world that would be a poor justification for re-implementing something yourself. But I am like you, and I understand that you want to implement something yourself (because you want to learn, you find it fun, you are a perfectionist, etc). As long as you do it on your own time and it's a personal project, go for it.
It would be worth studying Smarty to see how it works (not just the syntax but how it compiles templates, stores the compiled version etc). Are you comfortable writing a tokeniser/parser in PHP which can compile your template language and output PHP? If you are advanced enough to do it, do it. At the very simplest, you read in a tag like {foreach from=$something} and somehow translate it to <?php foreach ($something as $thing) { ?>. You check token types, etc to make sure the template tag is valid, and so on.

How to organize a PHP blog

So, currently I'm organizing my blog based on filename: To create a post I enter the name of the file. As opposed to storing the post in the database, I store them in PHP files. So each time I create a post, A new row in the table is created with the filename and a unique ID. To reference the post (e.g. for comments) I get the name of the current file, then search the entries table for a matching file name. The post ID of the comment matches the ID of that post.
Obviously this isn't the standard way of organizing a blog, but I do it this way for a few reasons:
Clean URL's (even cleaner than mod_rewrite can provide from what I've read)
I always have a hard copy of the post on my machine
Easier to remember the URL of a specific post (kind of a part of clean URL's)
Now I know that the standard way would be storing each post in the database. I know how to do this, but the clean URL's is the main problem. So now to my questions:
Is there anything WRONG with the way I'm doing it now, or could any problems arise from it in the future?
Can the same level of clean URL's that I can get now be achieved with mod_rewrite? If so, links are appreciated
I will be hosting this on a web host. Do only certain web-hosts provide access to the necessary files for mod_rewrite, or is it generally standard on all web-hosts?
Thanks so much guys!
P.S. To be clear, I don't plan on using a blogging engine.
As cletus said, this is similar to Movable Type. There's nothing inherently wrong with storing your data in files.
One thing that comes to mind is: how much are you storing in the files? Just the post content, or does each PHP file contain a copy of the entire design of the page as opposed to using a base template? How difficult would it be to change the design later on? This may or may not be a problem.
What exactly are you looking for in terms of clean URLs? Rewrite rules are quite powerful and flexible. By using mod_rewrite in conjunction with a main PHP file that answers all requests, you can pretty much have any URL format you want, including user-friendly URLs without obscure ID numbers or even file extensions.
Edit:
Here is how it would work with mod_rewrite and a main PHP file that processes requests:
Web server passes all requests (e.g., /my-post-title) to, say, index.php
index.php parses the request path ("my-post-title")
Look up "my-post-title" in the database's "slug" or "friendly name" (whatever you want to call it) column and locates the appropriate row that way
Retrieve the post from the database
Apply a template to the post data
Return the completed page to the client
This is essentially how systems like Drupal and WordPress work.
Also, regarding how Movable Type works, it's been a while since I've used it so I might be wrong, but I believe it stores all posts in the database. When you hit the publish button, it generates plain HTML files by pulling post data from the database and inserting it into a template. This is incredibly efficient when your site is under heavy load - there are no scripts running when a visitor opens up your website, and the server can keep up with heavy visitation when it only needs to serve up static files.
So obviously you've got a lot of options when figuring out how your solution should work. The one you proposed sounds fine, though you might want to give careful consideration to how you'll maintain a large number of posts in individual files, particularly if you want to change the design of the entire site later on. You might want to consider a templating engine like Smarty, and just store post data (no layout tags) in your individual files, for instance. Or just use some basic include() statements in your post files to suck in headers, footers, nav menus, etc.
What you're describing is kind of like how Movable Type works. The issues you'll need to cover are:
Syndication: RSS/Atom;
Sitemap: for Google;
Commenting; and
Tagging and filtering content.
It's not unreasonable not to use a database. If I were to do that I'd be using a templating engine like Smarty that does a better job of caching the results than PHP will out of the box.

How to template in PHP... the right way?

I'm starting to understand the importance of templating in PHP. I'm using PHP itself as a template engine to avoid learning any new language. I'm still not clear on one thing tho, although I have an idea about it. I would like to know what the experts do.
Should I create a full page template, with all tables, forms and everything else (including header and footer), or should I put all of my tables, forms, etc in their own file and then add them to the template as needed.
Here's a small example to clear things up...
Should I
a) create one page with all the tables, forms, and other elements in it and use that as a final product
// Set all the information
$template->title = $username;
$template->user_info = get_user($user_id);
$template->articles = get_articles($user_id);
$template->ads = random_ad($user_info);
// Load the template with everything already in it
$template->load('user_page.tpl')
$template->display();
OR
b) create every table, form, related block element in its own file and then use those to create a final product
// set the title and load the header template
$header['title'] = $username;
$template->load('header.tpl', $header);
// get the user info as an array and load into user profile template
$user_info = get_user($user_id);
$template->load('user_profile.tpl');
// load the new article form
$template->load('new_article_form.tpl');
// get the articles as an array of info and load into user articles template
$articles = get_articles($user_id);
$template->load('user_articles.tpl', $articles);
// get a random ad based on user info
$ads = random_ad($user_info);
$template->load('advertisements.tpl');
// load the footer template and display final page
$template->load('footer.php');
$template->display();
Where every file loaded contains a small portion of what needs to be displayed on the final page.
Because of the Dont Repeat Yourself technique, I would think B, but i would like to know which and why
I would personally say the first approach is best, because it keeps all documents and document fragments semantically complete.
The second approach means that you'll have a <div> in your header.tpl that is closed by a </div> in your footer.tpl (except likely there will be a few tags that applies to). This means if you change your layout, by adding a wrapper div (for example) somewhere, you have to remember to also close it in another file (or, depending on your layout, two or three different files).
It's worse with several different embedded files. Think of how hard it is to debug a site, when one file - that gets included conditionally - has an extra </div>. You get a vague bug report "sometimes the page looks completely messed up, doesn't matter what browser I use" that is very very hard to track down. It's MUCH worse if you're using table-based layouts..
Using the first approach, you can still use the DRY principle. You load the template into a variable. eg:
$userVars['name'] = $currentUser->name;
$templateVars['userinfo'] = $template->load('userinfo.php', $userVars);
...
$template->display('template.tpl', $templateVars);
You can continually nest documents that way. There are many benefits:
Each file is semantically complete HTML - all tags that are opened, are also closed in the same document. It's easy to edit one part of the layout without breaking (possibly unknowningly) anything else.
It's each to cache the output of certain templates, and re-use them
It's easy to apply AJAX to the site. For example, you have a stats.tpl template rendering inside a <div id="stats"> on the first page load. You also have a view that just renders the stats.tpl template by itself, and then use jquery to do $('#stats').load('/ajaxstats.php'), which refreshes that div but without repeating code at all.
Template inheritance for structures common to every template (e.g. layout; header/footer), and template embedding (i.e. including) for reusable bits (e.g. forms).
With approach A and without inheritance, you'd be either including common layout elements (which is IMHO ugly), or duplicating entire layout in every template (which is even worse). And plain approach B would create massive amounts of tiny template bits for everything, which may reduce maintainability.
And for that, I really recommend using real, dedicated templating engine instead of plain PHP. They make life easier (inheritance is one thing; another - variable auto-escaping).
template inheritance would probably make the cleanest code. you can do this now in straight php using PHP Template Inheritance
There is no good or bad solution. There are techniques and guidelines but in time you will learn what approach is better than others.
Just by looking at it i would say that the second approach allows you to be more flexible and breaks down the page into smaller parts. Smaller might some times mean more manageable.
Also the second solution also allows more than 1 persons working on the page since they will only need to work/change parts of the page and not the whole page.
regards,
As gregmac suggested, the first solution is probably preferable. Having said that, I would also suggest to have a look at the various PHP frameworks available, most of which implement templates using various techniques.
Have a look at this list for a start. You may also want to take a look at some stand-alone template engines, such as Smarty, in order to get some ideas or to avoid implementing your own engine.

Categories