How should I integrate some javascript into a php application? - php

I have a medium size legacy php application with almost no javascript integration. I've recently been learning javascript (yes actually learning it) using Douglas Crockfords excellent book and taken YUI as my library of choice. I've tried out a few things and got a few things working but now I want to integrate the various components etc into my application properly, my question is how to go about doing this for ease of maintenance and code reuse.
Currently the application consists of
php pages
smarty templates (html templates with some special template markup) for each section of a page so multiple templates may be used for a single page.
single css file.
I have the following ideas about how to integrate my javascript into the pages.
Write inline javascript in each smarty template with the code required for that section.
Write a seperate .js file to go with each smarty template that is linked in and then a single inline script to run it.
a seperate .js file for each php page which would have all the functionality required for the entire .php page. A small inline function would call whatever functions were required.
Something I havent though of?
Does this make any sense? Does anyone have a good suggestion for this?
Update:
One extra bit of info is that its an internal application, so its not so important to restrict everything to a single file.

Two other options:
A single JS file that contains all the JS for your entire site. Depending on your caching settings, you should be able to get the user to download just one file for the entire site and use a cached version for every other page.
Divide your JS up according to function, rather than page, and include whatever functionality each page requires. E.g. one page may require tabs, form validation and animation, while another may only require tabs.
Or you can have a hybrid of these: one JS file that contains the vast majority of your code and an extra file if needed for particular pages or templates.
None of the approaches mentioned are wrong (though I'd skip the inline JS one as much as possible); which one is best will depend on your precise situation and your personal preferences.

Firstly, most setups allow a master layout template in which you can place a common page opening or, alternatively, each template includes some global header.
That being said, you should do a combination of 1, 2 and 3:
Have a .js that is included in all templates that contains global functionality. Each template may also optionally have it's own .js specific to that page or section of pages. Finally, if there's tiny amounts of code specific to a page (or must be dynamically generated each time), it won't make sense to initiate another http connection for it so have that source be right in the template.

if you don't have a ton of javascript then create an external js file and include it in the header of the webpages and be done with it.

Related

Adding jQuery code in Joomla

I need to add this code to Joomla please
$(".item-204").append('<ul class="nav-child unstyled small"><li class="item-205"><a href="index.php?option=com_content&view=article&id=9" >رؤيتنا</a></li>');
what is the best way?
One way to do this would be to use Regular Labs ReReplacer which could be set up to replace the .item-204 code with .item-204 plus any additional code you require. I am assuming .item-204 is unique on the page.
The advantage of using this extension is that you don't have to find or update the core code. Updating core code is often considered bad practice as any future template or extension updates can undo your changes.
It's really just about adding this code to every page? Instead of adding another plugin so your site you can put your code in a script tag located in your templates main php file. This file is named index.php and is located here: /templates/[your template name]/index.php
If you want to do it even better, place this code in the templates JS file. Some of them have a file like /templates/[your template name]/js/custom.jswhich is a good place to add custom JS to.

Interchangability of PHP and JavaScript templates (prevent duplication)

I use a MVC PHP framework to keep my web applications as DRY as possible. All of my HTML templates are neatly tucked away in one folder in the application scope of my project.
The problem is that whenever I use a JSON string to build a page with AJAX, I need to reuse a lot of lines from these templates and copy them somewhere in my JavaScript files. This means there is code duplication between templates in my JavaScript files and templates in my PHP application.
I was wondering how this duplication can be prevented. One way is of course to load the template using AJAX, but then I would end up with a double AJAX request for one page. Furthermore, the PHP templates uses different tag styles to represent variables than MooTools, but the HTML setup is the same.
So to summarize: is there any neat way or a tool to prevent duplication of templates so one file could be used in both PHP and JavaScript? For the record: I use the MooTools framework to build my JavaScript files.
Edit
After some research, I found the best answer yet in my opinion. For those who are interested:
PURE
PURE separates HTML representation and JavaScript logic completely so you don't have to bother including HTML elements in your scripts. The template can simply be provided in the HTML file itself.
Example:
// JSON string
{ 'who': 'me' }
// In your rendered HTML page:
<div id="who"></div>
// After the JSON string is sent back
<div id="who">me</div>
Furthermore, it can be used by a wide selection of libraries: MooTools, jQuery, dojo, Prototype etc.
Interesting question that I'm struggling with sometimes too.
you can put your html in your javascript code, which is duplicating and which you want to avoid
you can load your html with a separate ajax call, which causes more ajax calls to be run, and possible slowing down of your app. you may want to avoid it.
you can pass your html within the Ajax call that will load the data. That way, you only have one call. Let your PHP open your templates, and add them to the data-json stream.
you can put the template inside your original html, put it as hidden.
I'd go for solution 3, or possibly 4 if templates are small and limited.
The JSon would then be something like {"data": ... your original data object, "templates":{...}}
You might be looking for a template langugage that is available for multiple languages so you can re-use your templates across language boundaries.
One such template language is {{mustache}}, works in both PHP and Javascript and many more languages.

How to get started with PHP themes?

I have a web application developed using PHP. I want my users to select themes for their pages throughout the application.
Where should I start before using PHP themes?
What should I know about Themes in a PHP application?
Edit:
My question about themes is only about changing the color of the layout, not the images.
Suppose My ADMIN user will have white and Orange, but my staff user will have white and green...
How it can be done in PHP with CodeIgniter?
There are lots of directions you can go with this.
1) "CSS ZEN"
This is where the markup remains unchanged, but you totally change the design just by using CSS and images. Demonstrated very well on http://www.csszengarden.com/
2) MVC Stylee
This is where you create a model that represents the page data and then pass it to a view, which contains some inline echo statements. The idea is that you could send the same model to a totally different view so it could look entirely different, HTML and all. Cake PHP is a good start for this: http://cakephp.org/
Example:
<div class="content">
<? echo $Page->Content ?>
</div>
3) Micro-Markup
With this method, you add your own "special tags" to an HTML page. You then read in your plain HTML page and replace the special tags with the information you want to display. This is good if you want your templates to be recognisable to HTML guys that don't know PHP and might break the PHP code in the MVC app.
Example:
<div class="content">
<#Content#>
</div>
Out of all of these, MVC is a very structured way of achieving what you want - however, I listed the other options as they cater for specific scenarios that might be relevant to you.
I have implemented the concept in all three of these, in situations that were appropriate for each.
Regarding The Edit In The Question
I imagine you'll have "something" that represents your user - so it is as easy as:
(In the event of just wanting to override a few settings...)
<link href="style.css" type="text/css" rel="stylesheet">
<?php if ($User->Type === USER_ADMIN) { ?>
<link href="admin.css" type="text/css" rel="stylesheet">
<?php } ?>
You can adjust this example in the following ways:
Use a switch statement if there will be many user types
If the replacement is total, rather than just a few overrides, you may want to completely swap the stylesheet.
You would usually set up template files that contain the HTML and CSS, and build in the PHP generated values at runtime.
The best approach to this is to have the theme reside in a separate directory, containing no code, just template variables like {mainmenu}, {backbutton}, {content} ... you get my drift. Those are then filled by your PHP script, possibly with the help of a template engine like Smarty (No need to re-invent the wheel here).
There is also the approach of having PHP markup directly in the template file(s) like echo $xyz; while this is a perfectly valid practice I use myself often, I recommend using a template engine over using PHP markup in the code if you want a solid, future-proof templating system because:
First, there is less that a designer can break when working on the HTML.
Second, having PHP markup in the code is a temptation to program PHP logic inside the template (loops, conditions) instead of properly preparing them in the PHP code at the point where the template variables are created. That is terrible for maintenance and the further use of your templates, because you have to replicate that PHP soup into every new template again. After all, you want to have a template engine so others can create new looks for your product, without having to know how to program it.
Third, with the templating engine based approach you have the possibility to add caching where necessary without any additional work. Not possible with the scripting approach. Yes, in a web application you won't be able to cache that much, but with a lot of data, there will be instances where it will help the user experience.
Fourth and least important, it makes your template less easy to export to other applications, and import templates from other applications.
The CSS Zen approach mentioned by Sohnee is great for websites, but is going to be too limited for a web application that uses complex input elements, JS based menus, and the like. It is too often that those elements need to be changed and customized in the markup.
If you have a look at my CodeIgniter Template library it briefly explains how you can set up themes and layouts (the equivalent of header & footer).
If you set up global code such as a Hook or a MY_Controller then you can dynamically set your theme based on the logged in user, the user type, etc.
Eg:
if($user->role == 'admin')
{
$this->template->set_theme('admin_skin');
}
else
{
$this->template->set_theme($user->theme);
}
That is just a VERY basic example of the sort of thing you could use this Template library for.
CMS Solutions
Magento and Wordpress package all theme related files into their own seperate directories. These contain the serverside code, stylesheets, images and javaScript for the theme. The user in effect chooses a directory to use which affects how the page is layed out and styled.
An easier approach
A much easier way to get started would be to accept that the actual content, e.g. HTML of a page would stay the same, but let the user choose from various CSS style sheets.
When choosing a style sheet the system could use JavaScript to load it in dynamically so that the user can preview the look they are choosing.
If you have really good semantic HTML it will be enough to change the CSS files. Unless the design changes are really heavy. Then it would make sense to provide PHP templates that are build with some sort of modules: variables which contain certain HTML structure like navigation or sidebar, etc.
For themes you do not need PHP. Just define your themes in CSS (the best way is one file for each theme) and use a simple JavaScript chooser like at this site: http://www.fotokluburan.cz/switchcss.js.

Are there any disadvantages of using PHP compared to html?

I have a few pages out (not too many though) and I was just thinking that I might want to change all of the pages to php instead of html. I am planning on using php in the future, I am just not quite ready yet to make it my full-time language. I know anythign you can do with html pages, you can do with php pages, but I just wanted to know, is there any reasons to stay with html compared to switching to PHP before my site gets too big and I wind up having to change 100 pages, and renaming hundreds of links?
The only reason I can think of is a small hit in performance.
Most web servers like Apache, LightTPD are configured to serve .html files as static files while .php files will have to first go through the PHP engine to be interpreted and only then delivered to the client.
Your pages will still be HTML. PHP allows websites to be generated dynamically, that is, you can display a username for users. However, what is sent to the browser is still HTML.
I recommend that you start switching to PHP because even if you choose not to use PHP, your pages will still work and render fine. However, if you stick with .html and then decide to switch to PHP, then you'll have to convert every single link. So convert now, and save time.
One thing I should note: It is possible, but usually not done, to have .html pages render as PHP by modifying server settings. However, in most cases, the .php is used, as most servers are already configured to run .php though the PHP engine. But in case anyone with a large site has this question, this is an option.
You pretty much answered your own question. If you ever reach the stage where you want to add dynamic content to an HTML document, you're going to need to change the file extension, or alter the webserver configuration to have PHP process .html files.
Generally, you will want every page to contain, if not dynamic content, then at least consistent content. Things like headers and footers, that require a massive amount of copy-pasting in straight HTML or a single include() in php. PHP allows for much cleaner organization and much less repetition, even if you're not after dynamic content for your pages.
The extension doesn't really matter. the PHP marker won't have any real effect until you begin embedding the tags into the files to engage the script processor.
Although it's true that you can do anything with PHP that you can do with HTML, the contrary is not true. With PHP you can do things that are not possible with HTML. Specifically, you can create dynamic pages with PHP, that is, pages whose contents are not fixed once you've written them.
If your pages are static, then you should continue to use HTML, if you need dynamic content, then you must use PHP (or another template/programming language).
why stay with just html when u can have both? u can have static html pages for static content and php pages for dynamic content. You can manage not just links but almost everything with php. I am creating a site with just 30 pages and I can say, while I do have both php and html, some things get out of hand (links, templates, data, etc). Imagine having 70 more...
Well, there aren't that many disadvantages maybe except for the fact that you might end up with this sort of code

reducing duplication in static HTML pages

I have a website which consists of a bunch of static HTML pages. Obviously there's a lot of duplication among these (header, menu, etc). The hosting company I plan to use supports PHP, which I know nothing about. Presumably PHP provides some sort of #include mechanism, but what changes to I need to make to my HTML pages to use it?
For example, suppose I have a page like this
index.html
<html>
<head></head>
<body>
<h1>My Common Header</h1>
</body>
</html>
Obviously I need to move the common part into it's own file:
header.html
<h1>My Common Header</h1>
Given the example above (and assuming all files are in the same directory):
What do I add within the body tag to get header.html included?
Do I need to rename index.html or add some special tags to indicate that it's a .php file?
Do I need to make any changes to header.html?
Update: I want to emphasise that my objective here is simply to find the lowest-friction means of reducing duplication among static HTML files. I'm a bit reluctant to go down the server side includes route because I don't yet know what type of server (IIS/Apache) I'll be hosting the files on, and whether includes will be turned on or off. I was drawn towards PHP only because it is about the only thing I can presume will be available that will be able to do the job. Thanks for the responses.
Thanks,
Donal
You are looking for include (or one of its derivative such as include_once, require, require_once):
header.php
<h1>My Common Header</h1>
index.php
<html>
<head></head>
<body>
<?php include('header.php'); ?>
</body>
</html>
And so on, for your footer for example.
You don't need to use PHP to get this functionality, and it's generally a bad idea to do so due to potential security concerns. Essentially, you're swatting a gnat with a nuclear bomb. If you're not using a dynamic language, then you're looking for server side includes.
In IIS, for instance:
<!--#include virtual="file.inc"-->
Be aware that you often have to configure the server to utilize them, as this feature is often turned off by default. Both IIS and Apache support server side includes, but they use different configurations.
You can find more information here:
Server Side Includes
EDIT: I don't mean that it's a bad idea to use PHP, just using PHP solely for including other files. It creates a larger attack surface by bringing PHP into the mix when it's not needed, thus the potential for security issues when the functionality of PHP is not required.
EDIT2: I think it's a bad idea to assume you won't be a target because of your size, and thus you can ignore security. Most sites are compromised by automated worms and turned into malware hosts, spam zombies, or pirated software/media servers. Apart from the fact that you might end up being involved with infecting others, your site can become blacklisted and it can cost you real money in bandwidth overage charges. We're talking hundreds or thousands of dollars.
Just because you're a small site doesn't make you any less of a target. Just being on the internet makes you a target.
Forget doing it on the server altogether.
If all you really want to do is maintain some static pages -- and don't anticipate ever having to really use PHP -- I'd just do it with Dreamweaver, which will allow you create and manage templates and variable content on your end.
No includes needed. No templating engine needed. (These would be overkill for what you are trying to accomplish.)
You should first change the file extensions of index and header to be .php, then you can do:
<html>
<head></head>
<body>
<? include 'header.php'; ?>
</body>
</html>
And your header.php file just has
<h1>My Common Header</h1>
While you can just use the "include", "require", or "require_once" directives to include things in one page, you might have better luck with a template engine like Smarty
While using an include file for the header is a solution I went a different route when I faced the problem several years back: I wanted all pages to use the same layout (which I assume is rather common ;-). Thus, as I only wanted to change the content of the page I made the page content the file that gets included and have a master template file that includes header and footer. For setting the page to be included I resorted to creating quite small php scripts that only set a variable that holds the page to get included. In some cases the page can also get named by a GET parameter. Of course this requires proper validation of that parameter. In the long run I don't need to worry about the HTML itself anymore -- all I do is write small snippets (which should be complete for themselves of course) that get included.
A possibly even better solution would be to use an existing template framework. Due to the contraints I had back then I wasn't able to do so, but I would do it when facing the same issue again.
Back in the day, I used SSIs (the "<!--#include virtual="file.inc"-->" method described above by Mystere Man) quite a bit for static HTML pages and I would definitely recommend using that.
However if you want to eliminate any uncertainty about whether support for that will be enabled on the server, you could develop your separate files locally and merge them into the resulting files before uploading to your server. Dreamweaver, for example, supports doing this in a seamless fashion.
Or you could do it yourself with a rather simple script in your language of choice by doing simple string replacement on markers in the files, replacing {{{include-header}}} with the contents of a "header.html" file and so on.
Edit
Oops! Somehow I didn't see Clayton's post with the same note about Dreamweaver.
OK this is a semi-programming related question only.
PHP does have include(), which is really easy to use, but it doesn't contribute to future maintainability. I wouldn't recommend it, especially for big sites.
I'm a pro-frameworks. I've used CodeIgniter, CakePHP and even Smarty template engine. If you are serious about PHP, do consider CakePHP. There's this "layouts" concept where you frame your header, footer, css, javascript outside of the main content; e.g. for the "about us" page, your content would be something like:
This is an about us page that tells you a whole bunch of stuff about us...
CakePHP takes this this content, and wraps your layout around it:
header
css
javascript
This is an about us page that tells you a whole bunch of stuff about us...
footer

Categories