build a webpage using php modules - php

I wish to build an HTML page by separating the layout from the content generation. I plan to have say a layout.php page with a matrix structure of div elements (say 3*3).
For div at location (1,3 - firstrow,third column), I wish to call an advertisement module which will return a travel ad. For div at location(2,3), the same module will be called but this time the HTML for a electronic product will be returned.
The intent here is to separate layout from content generation. So I can change the layout easily. For example, for location (2,3)instead of the static ad, i can call say a weather module that returns HTML showing weather data.
One way I can think of is to have an adv_module.php which has classes and member functions to return the appropriate ads HTML, with php code as below
i.e.
include_once(adv_module.php);adv1 = new ADV_MODULE(); echo adv1->getAd(category=travel)
:
:
include_once(adv_module.php);adv2 = new ADV_MODULE(); echo adv2->getAd(category=electronics
)
But then the HTML will have to be constructed within the member functions. This leads to a lot of ugly php code interspersed with the HEREDOC element to help construct the HTML. HEREDOC does not allow conditionals, loops ,etc
Is there a better way to do this? I wish to avoid templating (Smarty like packages) if possible.

Related

how to implement shortcodes in pages or blog?

I am using php framework laravel and I would like to implement shortcodes.
Does anyone have a suggestion how to go about implementing shortcodes that could be inserted by user into a page or blog post.
Example, lets say I would like to have a shortcode for gallery that has some images, something like
[gallery=id]
which would then display that particular gallery. Ofcourse I have gallery model and gallery & images tables.
My first thought is that I would have to scan the content of the page/post and look for shortcode and when I find a particular shortcode, then what? What do I insert instead of it?
I can't insert php code that loops through the gallery and produces output. I guess the best way to do it would be to run a function that returns complete html code that I insert instead of the shortcode.
Is it possible to return a view from a function and insert the result into a page/post?
Depending on what kind of "shortcode" you want, there are numerous options here:
Blade Directives
Blade Layouts
Blade Sub-Views
Blade Stacks
To be clear, I'm assuming you want to insert this into content blocks stored in a db or something, not in your exiting view files.
Assuming you want inject the text into your view for display, you could allow content creators to use a templating format like mustache (https://en.wikipedia.org/wiki/Mustache_%28template_system%29) with server side callbacks/helpers/partials (in the view) to populate your own custom tags with dynamic content (gallery links in this case).
Main Points
I'd stick to a basic well known templating format like
mustache for this. In laravel, allow to Blade templating notation, it sounds like you want for this case to register a Blade::directive: https://www.laravel.com/docs/5.3/blade#service-injection.
I'd try to use an existing library if one such exists before
attempting to create your own short-tagging markup parsing /
callback paradigm. Blade has functions and methods handle such callbacks.
#2 is not necessary, but highly recommended, but #1 should be considered near religious.
UPDATE: as point out in other answers, Laravels built-in templating Blade, has this functionality, so stick to it's format and functionality.
Here's my suggestion (in pseudo-laravel/php):
Assume your marked up content from model pulled into the controller is in $content['blade_markedup_content' => 'here is my new gallery: #gallery(1)'] to be passed to the view.
Add a Blade directive #preprocess() to and in the template/view use <p>#preprocess($blade_markedup_content)</p> in place of just substituting raw <p>{{$blade_markedup_content}}</p>.
In the respective callback function for the #preprocess() directive
Instantiate a new $my_compiler = new BladeCompiler();
Register to this new blade compiler directives to handle the like #gallery(1) you put in your blade_markedup_content
return from the #preprocess() with $my_compiler->compileString($blade_markedup_content);
Viola... In theory, this should result in a parsed and substitute string from #preprocess($blade_markedup_content) in the original template.

CakePHP: How to show the same query data in all my views, directly in the layout file

I'm creating a website with CakePHP; the problem now is that I want to show in the website footer (that will be visible on all the pages), the result of a query (e.g. "Most popular products").
What is the correct way with CakePHP to achieve this?
At the moment I created a mostPopularList() in my Product controller and a most-popular-list.ctp view that only outputs an <ul> list, thinking that then I could include the output of this file in my layout (default.ctp), but I didn't find the CakePHP way to do that.
Thanks!
Use a view cell or call the query in the AppControllers beforeRender() callback and set it there to the view. Taken from the documentation:
View cells are small mini-controllers that can invoke view logic and render out templates. They provide a light-weight modular replacement to requestAction(). The idea of cells is borrowed from cells in Ruby, where they fulfill a similar role and purpose.
View Cells
Controller::beforeRender()
If this is needed on really every single page I would probably go for the beforeRender() callback, easy to do and change globally.

Code Resuable HTML UI elements PHP

I'm new to PHP and I am currently creating a PHP web application for an assignment at university. During the development I had realized that alot of elements in the user interface were being replicated in different sections of my application. For example I may have a hyperlink button in a Clients Page called 'New Client' (<a class="bigbutton" href=".......">New Client</a>) and another hyperlink button in a projects page called 'New Project' (<a "bigbutton" href=".......">New Project</a>).
Normally, I could just copy the html that constructs the buttons on the Clients Page and Change the content to suit the 'New Project' button in the projects page. Now If I was convert the hyperlink button to the tag, I would have to go to every instance of that particular button to replace the tag with a tag and if this button exists on so many pages, then updating would be time consuming.
That was just a simplistic example, then I have to think for other repeated elements across multiple pages such as breadcrumbs, list tables etc.
Is there any way to code in a way where I can actually reuse these UI elements that may be worthwhile to look at? Perhaps I could try to code each of these elements into classes, but right now I am not sure.
Any hints, pointers or resources would very helpful and appreciated.
Thanks guys.
You can make PHP functions which echo the HTML when called, optionally including some config stuff e.g.
function make_button($id, $label) {
echo '<button id="'.$id.'">'.$label.'</button>';
}
This can be done for large chunks of the page, or just small bits. Some systems I've used have a html_writer class for this sort of thing, others use render methods where you pass an object in and it'll pass back a string of HTML representing that object on a page.
Up to you which you prefer. Also good to make small functions which can be reused in larger functions like:
function make_buttons_from array($array) {
foreach ($array as $id => $label) {
$this->make_button($id, $label);
}
}
The examples here echo their output, but you can also use string concatenation to assemble the pieces. Again, your call. There's not really a right way.
There's all sorts of specific avenues you could take, but the basic approach is to have a set of templating functions or methods in a class that build all of the common elements of your pages. Anything that's shared (or has only minor changes) from page to page is defined once in these functions, and you simply call the functions from each page, providing enough information to allow the function to differentiate how it should display its content depending on the details of the page that's calling it.
If you've got a change to a common element, you just go to the function and change it, and in this manner it's copied to all of the pages.

Converting a site from HTML to Smarty

I have a series of HTML pages which I am converting into Smarty syntax since I've learnt this. This site is a fairly old one in design terms, no include etc. - even though our .htaccess allows us to treat PHP as HTM extension.
I've saved a few as .tpl pages, but what's the best way to go about converting it into full-scale templating?
I've been slowly, but tediously, splitting pages into .tpl files, although not sure if that's the right way to do it... the site is a jointly-created one, dating back to 2006 originally as pure HTML.
I'm using a templating engine because that's what the original site-owner wanted, and we're both competent at using a templating engine.
The manual on Smarty was useful; but I'm wondering how to do a Smarty pagination script where the data is paginated like this for database results (moving some data into a new database that was formerly static data enclosed in < li > tags), rather than 1-10, 11-20 etc.:
http://i44.tinypic.com/5uh7nk.jpg
If there's another solution (for now we don't quite need CodeIgniter etc.) I'd appreciate the help! ;)
The SmartyPaginate plugin may help. This was written by one of the original Smarty developers. I'm not sure if it is compatible with Smarty 3 though, if that is what you're using.
The other possibility would be to create a template that outputs the pagination, and accepts some parameters to set the options.
e.g.
{include file="paginator.tpl" curpage="3" perpage="50" numitems="3428" link="showitems.php" param="p"}
Where...
curpage = the current page being viewed, this would be set by PHP.
perpage = how many items to show per page - this is probably a static value set by php, or from user preferences
numitems = how many total items there are - this is calculated by php/sql and passed to template
link = the page to link each page to
param = the parameter to use for the page number, this is used by PHP to get the page to be viewed. i.e. items.php?p=1
That said, you would use PHP code to check to see if a page number was set in the URL, and then check to see if the page number is valid and within the acceptable range.
Your actual page content would just loop over an array of items which would be the results from the database. Depending on what set of results was fetched, it will be showing items from the given page.
If the SmartyPaginate plugin won't work, you could probably look at it for help with the process of pagination and adapt it to your needs.

Create and populate landing pages dynamically using feed

I am trying to create multiple landing pages populated dynamically with data from a feed.
My initial thought was to create a generic php page as a template that can be used to create other pages dynamically and populate them with data from a feed. For instance, the generic page could be called landing.php; then populate that page and other pages created on the go with data from a feed depending on an id, keyword or certain string in the url. e.g http://www.example.com/landing.php?page=cars or http://www.example.com/landing.php?page=bikes will show contents that are either only about cars or bikes as the case may be.
My question is how feasible is this approach and is there a better way to create multiple dynamic pages populated with data from a feed depending on the url query string or some sort of id.
Many thanks for your help in advance.
I use this quite extensively. For example, where I work, we often have education oriented landing pages, but target each landing page to different types of visitors. A good example may be arts oriented schools looking for a diverse array of potential students who may be interested in a variety of programs for any number of reasons.
Well, who likes 3d Modelling? Creative types (Generic lander => ?type=generic) from all sorts of social circles. Also, probably gamers (Gamer centric lander => ?type=gamer). So on.
I apply that variable to the body's class, which can be used to completely reorganize the layout. Then, I select different images for key parts of the layout based on that variable as well. The entire site changes. Different fonts can be loaded, different layout, different content.
I keep this organized via extensive includes. This sounds ugly, but it's not if you stick to a convention. You have to know the limitations of your foundation html, and you can't make too many exceptions. Sure, you could output extra crap based on if the type was gamer or generic, but you're going down the road to a product that should probably be contained in its own landing page if it needs to be that different.
I have a few landing pages which can be switched between several contents and styles (5 or 6 'themes'), but the primary purpose of keeping them grouped within the same url is only to maintain focus on the fact that that's where a certain type of traffic goes to in order to convert for this specific thing. Overlapping the purpose of these landing pages is a terrible idea.
Anyway, dream up a great template, outline a rigid convention for development, keep each theme very separate, and go to town on it. I find doing it right saves a load of time, but be careful - Doing it wrong can cost a lot of time too.
Have a look at htaccess URL Rewrite. Then your user (and google) can use a url like domanin.com/landing/cars but on your server the script will be executed as if someone entered domain.com/landing.php?page=cars;
If you use feed content to populate the pages you should use some kind of caching to ensure that you do NOT reload all feed on every requests/reloads the page.
Checking the feeds every 1 to 5 minutes should be enough and the very structure of feeds allows you to identify new items easily.
About URL rewrite: http://www.workingwith.me.uk/articles/scripting/mod_rewrite
A nice template engine for generating pages from feets is phptal (http://phptal.org)
You can load the feet as xml and directly use it in your template.
test.xml:
<foo><bar>baz!!!</bar></foo>
template.html:
<html><head /><body> ${xml/foo/bar}</body></html>
sample.php:
$xml = simplexml_load_file('test.xml');
$tal = new PHPTAL('template.html');
$tal->xml = $xml;
echo $tal->execute();
And it does support loops and conditional elements.
If you are not needing real time data then you can do this in a few parts
A script which pulls data from your rss feeds and stores the data somewhere (sql db?), timed by something like cron. It could also tag the entries into categories.
A template in php taking the url arguments and then adding the requested data and displaying it for the user. Really quite easy to do with php, probably a good project to use to learn as well if you are that way inclined

Categories