I'm looking for recommendations on how to do some reporting in PHP. Specifically, I need PDF rendering and I would like to separate the presentation from my code as much as possible (templates of some sort?).
I've recently received a PHP4 code-base on the job and am in charge of upgrading to PHP5. The reports currently are created via TCPDF which are driven from HTML generated straight from PHP. The upgrade process is proving extremely challenging. I'm running into multiple problems with TCPDF where it will just go into an infinite loop and never return. Through some troubleshooting and forum posts, it appears we're doing some stuff that TCPDF4 with PHP4 didn't have a problem with but TCPDF5 and PHP5 does. Unfortunately, rather than error on whatever rules we're breaking, I just get infinite hangs. Our in-house code could use some refactoring and I feel a re-write could mitigate many of these problems, however I'm not opposed to looking beyond TCPDF right now.
Our code also has a lot of the HTML generation mixed in with the rest of the reporting features. I would really like to separate this out so that little to no PHP code is required when editing or creating a report. I don't need anything too fancy for the report. Needs to support basic data tables and multiple horizontal panes on a single tab. There are charts but they are currently generated by a separate package and just read directly as an image. Suggestions on the best way to re-do these reports? Thanks.
You can use PHP as a template engine, and than you can convert the HTML output to a PDF.
Here are the options for PHP templating:
Use Smarty, it's pretty easy and has it's own template language, but I think that it's for your usages a bit overhad.
Or you can use just plain PHP, just put the templates code into a sepearated directory and create a function render_template('template_name.php') or something like this.
In your case, I think that you could write your own class for the handling of reports. Here just a simple sketch of the usage:
<?php
$report = new Report(1234); // report id
$report->template = 'default'; // or something different
$report->addField('Users', array('Claire', 'Fred', 'Kevin'), array('renderArray' => true));
$report->addField('Note', '<p>This report was generated automatically.');
So, eventually you can use some of the simple ideas behind this simple sketch.
I hope that I understood your question correctly, and that I could help you with this answer.
I've created some dynamic PDF using multiple classes : separating PDF and Pdf design, from data access and management
I have one abstract class that you can use for all your reports. this class handles the PDF generation (all the set up), and you may design some styles ("writeTitle1()"), or helper methods to render data. ex "writeReportTable()"
If you plan on keeping a system that converts html2pdf, this class can generate some html too, or call any templating engine.
In my design, this class generally wraps the PDF engine. (I often use Cezpdf)
Then for each report, a child class that focuses on data management : getting and formatting the data, then calling the rendering method.
This is a first step to gain some visibility : independant layers.
Related
I know things like these have been asked and answered several times before, is it just that I can't grasp the idea easily or too hard to accept that things are really like this and that.
I know that HTML is used for Front-End where the tedious work is done in the Client, and PHP is working behind the scenes (Server-Side). With so many regulations, instruction, standards, so on and so forth.. I believed I have already confused myself with these stuffs, making things (new and old) hard for me to chew and understand especially when it comes to their best uses...
Anyway, I have created a web application based on the concept of MVC tho I didn't used the strong fundamentals of the topic nor a framework, I separated the Logic, Rules and Design concerns by my own.
Unfortunately, I wound up with some issues similar to which is the right way to do the things, how this should be implemented, etc...
I end up needing to template the HTML, however, since I've used HTML as HTML itself, I end up updating/editing each and every affected file (for. eg. a web page header), unlike when I used PHP before, literally a file with a .php extension, where I can fully utilize templating, however, i read somewhere that it is not a good practice because it breaks the HTML.. so which one should I follow and how can I solve my problem, should I move to .php and then create a template page, or is there a way I could do such with HTML? if there is any, how can it be done?
Please for the meantime, don't point me to frameworks available, I want to understand basic things first before studying frameworks...
Anyone, please...
Edit...
so this is just fine and that it doesn't have any drawbacks...
main.php
<?php php stuffs ?>
<html>
<body>
HTML stuffs and some <?php php stuffs ?>
</body>
</html>
HTML has no templating capability.
It has frames and iframes, but they come with significant drawbacks and only provide include functionality.
You should use a proper templating language. This can run on the client, server or build system.
I'd recommend against running it on the client. It adds an unnecessary dependency that your visitors (including search engine indexers) have to fulfil.
PHP will do the job (it straddles the border of being a programming language and a templating language). My personal preference is for Template-Toolkit.
TT can run in your build system via the ttree utility, or you can run it on your server. There is a tutorial covering how to build websites using it.
If, and when, you move to building websites with more demanding server side requirements, then you can continue to use TT as it is supported but most of the web frameworks in Perl land (e.g. the dancer module for TT and the catalyst module for TT. Note that those links go to the hardcode documentation for the modules, and if you plan to use one of the frameworks you should start with a higher level tutorial)
HTML is a markup language - in other words it can mark up text to display to the user.
It cannot do any of the dynamic type functions you might need in a web application - like updating the date, for example.
So it is best to think of HTML documents, just like you might think of a Word document, a load of text that is displayed to the user.
As soon as you want to start using templates to display dynamic information (stuff from a database, maybe), you're going to need a scripting language. PHP is good for this.
I've had good experience with Smarty - a php templating engine.
On a side note, learning a framework can be a really useful part of the learning the basics. Most frameworks force you to do things in a good way, and sometimes the things they make you write in your code may seem a bit strange or illogical, suddenly one day the penny will drop and you'll realise why what you've been forced to do is sound from an engineering point of view.
You can look # javascript templating. I suggest you to give a try to http://mustache.github.com/
Modest is a template system that's supposed to look and feel like HTML.
The most common way to do HTML templating with PHP, is to use one of these popular templating engines :
Smarty
Twig
Latte
Mustache
Alternatively, you can just put placeholders in your HTML that look something like <% variablename %>. Just load your HTML, do a regex do find all placeholders and replace them with the corresponding variables.
Alternatively, you can load your HTML, parse it as a DOM document and then modify your DOM. I created the library DOM Query to be able to do this with a jQuery-like syntax, but you could use vanilla PHP or one of several other libraries as well.
Alternatively, you can do some HTML templating in frontend with JavaScript. If you want to do HTML templating both on frontend and backend, you might want to consider using Mustache, because Mustache templates can be used both in frontend (with JavaScript) and in backend (with PHP).
how can i isolate the style (css+html) from php, like put in the php file just some lines including by it the whole style or theme.
ex:
echo
eval_template("header") .
eval_template("body") .
eval_template("footer")
So in future i can change the whole style without touch the php files
any idea ?
there are many ways how you could do this...
Here's a tutorial on templating in plain PHP
http://www.phpro.org/tutorials/Introduction-to-PHP-templating.html
You can also take a look at the many template engines out there.
twig is one of them: http://twig.sensiolabs.org/
Personally, I enjoy to do it manually.
PHP should not return both css and html code, or even better, it shoukd not return client-side code at all but rather dependencies to specific parts. You never want to modify a file that contains a lot of different things.
To separate css+html from the php code, what I usually do is a hierarchy done with include("..."); and include_once("..."). For example : include_once("header.php") > include("menu.php") > html semantic with css classes correctly initialized according to current context.
Then you import your css / js external scripts in header.php so that you never have to modify the whole thing unless everything changes or if you have a complete feature to add to the website. Same is possible for every sections of the website.
Hope this helps, for me it is incredibly reducing debug-time since everything important has to be done only once, then at the top of it, you can seperate as you wish.
There are a lot of template engines you can use to do that, i prefer use twig, that is integrated with symfony2 framework.
Twig is wonderful because is very easy to use and very flexible, you can use inheritance to create a common layout which can be extended and overwriten in some some part using special tags. This is a guide i've find on Symfony website but is very usefull to understand the logic behind twig: http://symfony.com/doc/current/book/templating.html
I've been on a project with a buddy who is leading us with Middleman. We are coding in HAML and SASS and he's obviously a Ruby Dev. I'd like to know if there's ANY type of equivalent for PHP? I'm going to eventually lead a team and I'm much more comfortable with PHP than Ruby.
I'd like to have a layout file (like Zend's layout file)
I'd like to...at one command, convert all of the source files from PHP to static HTML and place those static files in a 'build' folder so we can hand it over to the client.
Anyone know of some cool things out there to make this happen? Thanks a bunch!
A project I work on, www.findbigmail.com, was written completely in PHP to start with and then I did some Ruby/Rails work for a different project, and coming back to PHP was a grind. After using HAML, SCSS and other wonderful things like CSS and JS minify, oh and Compass to build sprites, it was painful to go back to PHP and work again in PHP files with embedded HTML etc.
So, driven by pure slothfulness, I looked around and found MiddleManApp (MM) - after a couple of side trips along the way.
Now we have a very strong separation between what is now a mostly static html site built by MM, with some PHP files that are POSTed to and then redirect back to html pages. Where we need more dynamic behaviour, we've added javascript to the pages and have them call PHP API wrappers around our pre-existing code.
Our site performance has jumped hugely (doh, now its all static html), and its poised to take another jump when the next MiddleMan version comes out with its improved cache-busting abilities inherited from the Rails 3.1 asset pipeline. E.g. we'll be able to reference main.css in our source scripts (which itself is made up of sub-scss files like _index.scss, _pricing.scss) and it will be built with references to main-2348jlk23489kdj.css -- allowing us to set the server to cache for a year and/or deploy many more files to CDN.
Our engineering performance is way up too. We're no longer reluctant to touch UI code for fear of introducing a syntax error into the PHP code. And no more mismatched HTML tags to cause grief. The other PHP developer wasn't familiar with the Ruby/Rails derived toolchain, but has quickly become proficient (though he is a rockstar developer, so that's not too surprising!)
Coming soon is i18n support. Most of that is in MM already and hopefully Javascript support
real-soon-now.
We also explored generating pages from HAML with PHP added to them. We decided it was probably quite simple - e.g. add a ":php" tag to the HAML pipeline and then use .php partials as needed. But, we found that between Javascript and wrapping the existing PHP code as an "engine API", we were able to keep the codebases neatly separated -- which we found we prefer overall.
I hope this helps! Happy to explain more.
There is one for PHP called Piecrust.
I ended up choosing Middleman for the bundled coffeescript, sass, etc., but Piecrust is well done.
http://bolt80.com/piecrust/
PHP can render static HTML from PHP code quite easily:
Easiest way to convert a PHP page to static HTML page
Generate HTML Static Pages from Dynamic Php Pages
PHP - How to programmatically bake out static HTML file?
You could wire up something with existing template systems like Twig or use PHP Markdown to more or less mimic what Middleman is doing and create static HTML pages from your source files.
EDIT: As Hari K T mentioned above, http://www.phrozn.info/en/ does exactly this.
I was wondering if there was a good source on how to build tables using the PDFLib for PHP. I am planning to populate a PDF Document with a Database Table (well a few that I join together to create a new view) and I wanted to make it a PDF document for the web. I've been searching all over and I find plenty of information on PDFLib except how to create a table with it.
I've checked out the PDFLib commands on PHP.net and also can't quite get a clear grasp of what's needed.
I've worked with PDF generation a few times in the past, and generally find it to be a huge pain in the neck.
PDFLib's documentation http://www.pdflib.com/fileadmin/pdflib/pdf/manuals/PDFlib-8.0.2-tutorial.pdf starts explaining what you're looking for in section 8.2, page 193. You'll be creating multi-line flows. The code there looks intimidating, but take some time to work through it, it's pretty close to what you'll end up using.
I may be able to find some code later, but I forget what library I was using. For now a few tips:
Work it out on paper, just like their marked up examples. Where you want things to start, end, and such.
Use clear variable names to store those offsets. Not constants!
Find good extreme examples to test with while developing. Developing with text like "test" to find out later you need to support "I am the very model of the modern major general" may throw off your entire flow, and require you to start from scratch.
Some libraries "support" HTML embeds, including HTML tables. This siren song is sweet, but will lead you into the razor sharp rocks. Every library I've used supports them a little bit, but then you run into a wall where you can't get the next little tweak without dropping tables and reverting to native functions. They've been a huge waste of time to play with, one and all.
update
I've found my most recent code iteration, we used the library from http://www.tcpdf.org. It worked, mostly. I dealt with a lot of inconsistencies in where the cursor was left after writing multiple lines of text to a page. I ended up ripping out anything that used their multi-line code and writing my own. That done it got pretty easy to work with.
Table handling in PDFlib is made extremely difficult. Tables work, but in cases where you have multiple tables in top of each other and want the below one tables to be always at a certain distance of upper table's bottom line or want to use nested tables, you are in trouble. These like behaviors can be made, but the code is complicated. WHY pdflib team didn't take usage behaviour of html tables, where they have worked well two centuries.
Because html tables are easy to use, one good method is to use phantomJS to generate pdf from html. PhantomJS uses webkit for page rendering and supports html5+css3+svg+canvas. And in addition to pdf, it can output png, jpeg and gif.
Here is an example of using phantomJS to generate PDF-invoices:
http://we-love-php.blogspot.fi/2012/12/create-pdf-invoices-with-html5-and-phantomjs.html
So I have seen some comments on various web sites, pages, and questions I have asked about separating php and html.
I assume this means doing this:
<?php
myPhpStuff();
?>
<html>
<?php
morePhpStuff();
?>
Rather than:
<?php
doPhpStuff();
echo '<html>';
?>
But why does this matter? Is it really important to do or is it a preference?
Also it seems like when I started using PHP doing something like breaking out of PHP in a while loop would cause errors. Perhaps this is not true anymore or never was.
I made a small example with this concept but to me it seems so messy:
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
?>
<b>Fatty has </b><?php echo $cookies; ?> <b>cookies left.</b><br>
<?php
}
?>
Are there instances when it is just better to have the HTML inside the PHP?
<?php
$cookies = 100;
while($cookies > 0)
{
$cookies = $cookies -1;
echo'<b>Fatty has </b> '.$cookies.' <b>cookies left.</b><br>';
}
?>
When people talk about separating PHP and HTML they are probably referring to the practice of separating a website's presentation from the code that is used to generate it.
For example, say you had a DVD rental website and on the homepage you showed a list of available DVDs. You need to do several things: get DVD data from a database, extract and/or format that data and maybe mix some data from several tables. format it for output, combine the DVD data with HTML to create the webpage the user is going to see in their browser.
It is good practice to separate the HTML generation from the rest of the code, this means you can easily change your HTML output (presentation) without having to change the business logic (the reading and manipulation of data). And the opposite is true, you can change your logic, or even your database, without having to change your HTML.
A common pattern for this is called MVC (model view controller).
You might also want to look at the Smarty library - it's a widely used PHP library for separating presentation and logic.
Let's make it clear what is not separation
you switch from php mode to html mode
you use print or echo statements to write out html code
you use small php snipplets inside html files
If you do this, there is no separation at all, no matter if you escape from php to html blocks or do it the other way and put php code into html.
Have a look at a good templating engine, there are a plenty of reasons in the "why use ...." parts of the manuals. I'd suggert www.smarty.net especially http://www.smarty.net/whyuse.php
It will answer all your questions now you have.
It is very important to separate application logic from presentation logic in projects. The benefits include:
Readability: Your code will be much easier to read if it does not mix PHP and HTML. Also, HTML can become difficult to read if its stored and escaped in PHP strings.
Reusability: If you hard-code HTML strings within PHP code, the code will be very specifc to your project and it won't be possible to reuse your code in later projects. On the other hand, if you write small functions that do one task at a time, and put HTML into separate template files, reusing your code in future projects will be possible and much easier.
Working in a team: If you are working in a team that contains developers and designers, separation of application logic and presentation templates will be advantageous to both. Developers will be able to work on the application without worrying about the presentation, and designers (who don't necessarily know PHP very will) will be able to create and update templates without messing with PHP code.
for pages that contain a lot of HTML, embedding PHP code into the page could be easier. this is one of the first intentions behind PHP. anyway when you are developing an application with lots and lots of logic, different types of connectivity, data manipulation, ... your PHP code gets too complicated if you want to just embed them in the same pages that are shown to users. and then the story of maintenance begins. how are you going to change something in the code, fix a bug, add a new feature?
the best way is to separate your logic (where most of the code is PHP) in different files (even directories) from your page files (where most of the code is HTML, XML, CSV, ...).
this has been a concern for developers for so many years and there are recommendations to handle these general problems, that are called design patterns.
since not everyone has the experience, and can apply these design patterns into his application, some experienced developers create Frameworks, that will help other developers to use all the knowledge and experience laying in the hear of that framework.
when you look at toady's most used PHP frameworks, you see that all of them put code into PHP Classes in special directories, make configurations, and .... in none of these files you see a line of HTML. but there are special files that are used to show the results to users, and they have a lot of HTML, so you can embed your PHP values inside those HTML pages to show to users. but remember that these values are not calculated on the same page, they are results of a lot of other PHP codes, written in other PHP files that have no HTML in them.
I find it preferable to separate application logic from the view file (done well with CodeIgniter framework with MVC) as it leaves code looking relatively tidy and understandable. I have also found that separating the two leaves less margin for PHP errors, if the HTML elements are separated from the PHP there is a smaller amount of PHP that can go wrong.
Ultimately I believe it is down to preference however I feel that separation has the following pros:
Tidier Code
Less of an Error Margin
Easy to Interpret
Easier to change HTML elements
Easier to changed Application Logic
Faster Loading (HTML is not going from Parser->Browser it goes straight to browser)
However some cons may be:
It only works in PHP5 (I Believe, could be wrong, correct if needed)
It may not be what one is used to
Untidy if done incorrectly (without indentation etc, however this is the same with anything)
But as you can see, the pros outweigh said cons. Try not to mix the two also, some separation and some intergration - this may get confusing for yourself and other developers that work with you.
I hope this helped.
Benefits of the first method (separating PHP and HTML):
You don't need to escape characters
It's also possible for code editors
to highlight/indent the markup.
It's arguably easier to read
There is no downside to this method,
compared to the second method.
Functionally: they both will work, so ultimately it is a preference.
Yet, you might consider that comments are a preference as well, your code would compile and run exactly the same without comments. However most people would agree comments are essential to writing and maintaining good code. I see this as being a similar subject matter. In the long run it will make it easier to read and maintain the code it if the two are separated.
So is it important? I would say Yes.
I kick off with: the first one you can open in a WYSIWYG editor, and still see some markup, which might makes it easier to maintain.
It says that what you put in echo '' it is first processed by the programming language and then sent to the browser, but if you directly put there html code without php, that code will load faster because there is no programming involved.
And the second reason as people above said is that you should have your 'large programming code' stored separately of the html code, and in the html code just put some calls to print results like 'echo $variable'. Or use a template engine like Smarty (like I do).
Best regards,
Alexandru.
Ouch!
All of the examples in your question are perfectly impossible to read. I'd say, you do yourself and those, who might read your code a great favour and use a template engine of sorts, say, Smarty. It is extremely easy to set up and use and it WILL separate your code from presentation. It doesn't require you to put everything in classes, it just makes sure, that your logic is in one file and presentation - in another one.
I don't know how in php but in asp.net separation has the following advantages.
1. separated code is easy to understand and develop
2. designer can work in html in the same time developer can write a code