How to translate XSLT into (partial) PHP? - php

Due to a work I need done, I need to do a translation between two different programs.
A program defines data translations as XSLT and the other program uses a different format.
The program in between was chosen to be written in PHP.
I have no possible saying or vote on what is above for reasons I'm not allowed to tell.
The XSLT used is a small subset of all tags that are defined for XSLT:
for-each, if, choose, value-of
For those, I can just do a simple handling with a switch.
My main issue, though, is the when#test. The program may use any of XSLT's functions.
Now, the number of functions that XSLT has is very extensive and it seems that reproducing or mapping all of those one-by-one is a wrong way to solve this. Is there any better way of translating XSLT's functions into PHP functions (not necessarily php native functions) that I'm failing to find?
I already tied looking at the XSLTProcessor class but it doesn't seem to have any way of achieving what I want...
NOTE: Currently I'm reading the XSLT with PHP's DOMDocument object.

Related

PHP - get all declared resources (traits, classes, functions and constants) within a given script?

I designed a PHP 5.5+ framework comprised of more than 750 different classes to make both web applications and websites.
I would like to, ideally, be able to reduce its size by producing a version of itself containing just the bare essential files and resources needed for a given project (whether it's a website or a web application).
What I want to do is to be able to:
reduce the amount of traits, classes, constants and functions to the bare essential per project
compress the code files to achieve a lesser deployment size and faster execution (if possible)
So far, I've got the second part completed. But the most important part is the first, and that's where I'm having problems. I have a function making use of get_declared_classes() and get_declared_traits(), get_defined_constants() and get_defined_functions() to get the full list of user-defined classes, traits, functions and constants. But it gives me pretty much EVERYTHING and that's not what I want.
Is there a way to get all defined classes, functions and constants (no need for traits as I could run class_uses() on every class and get the list of traits in use by that class) for a single given script?
I know there's the token_get_all() function but I tried it with no luck (or maybe it's I'm using it the wrong way).
Any hint? Any help would be greatly appreciated :)
You can use PHP Parser for this. It constructs abstract syntax trees based on the files you supply to it. Then you can analyze its output for each file, and produce a report usable to you.
Other than that, you can use token_get_all() approach you've mentioned already, and write a small parser yourself. Depending on your project, this might be easier or more difficult. For example, do you use a lot of new X() constructs, or do you tend to pass dependencies via constructors?
Unfortunately, these are about the only viable choices you have, since PHP is dynamically typed language.
If you use dependency injection, however, you might want to take a look at your DI framework's internal cache files, which often contain such dependency maps. If you don't use such framework, I recommend to start doing this, especially since your project is big and that's where dependency injection excels at. PHP-DI, one of such frameworks, proved to be successful in some of my middle-size projects (25k SLOC).
Who knows? Maybe refactoring your project to use DI will let you accomplish the task you want without even getting to know all the dependencies. One thing I'm sure of is that it will help you maintain it.

linked list php spl or custom?

I need to use a double linked list using PHP for my script so I dug on the web and found a very good one:
http://www.codediesel.com/algorithms/doubly-linked-list-in-php/
this one made me understand how it works, and how the elements are tied together etc...
Now, PHP has its own set of SPL functions for double linked lists, which makes it very easy but on the other hand, I have to trust what php do and I am also limited to what they have.
Should I use instead the one from PHP? Or should I use this code in the link and in case I want to customize it, can I easily?
Use whatever is more appropriate for you, but here are some considerations:
PHP SPL code is maintained and community-vetted, code from a random blog is typically not
the SplDoublyLinkedList is already there, no extra code to maintain
the SplDoublyLinkedList is only there if your PHP version is current
you can extend and customize the SplDoublyLinkedList class to your liking
the SplDoublyLinkedList may be faster, since it's native code (I guess); benchmark if this an important factor to you

Why are functions and methods so large in PHP?

I do not have a ton of PHP experience, but whenever I have been given legacy code or even recent PHP code, one thing that always strikes me is how BIG the functions are. In seems like every .php file as at least one page-long function in it. Is there any intrinsic reason why functions and methods in a dynamic, high-level language like PHP should be so huge? The only kind of code I can think of that exceeds it in lines-per-function is C code. Why does PHP code always look this way?
No, there isn't any reason why the functions should be larger in PHP.
If the functions are huge, they were the result of a bad design.
Perhaps you're dealing with PHP scripts written by people with little programming experience, who didn't know how to write well-structured programs.
Why does PHP code always look this way?
Because you haven't seen good PHP code.

Embedding PHP in XML

I am trying to execute PHP code in XML Below is the code is there better way of executing as we are using eval and far as I know it degrade the performance 80-85% as it is supposed to be used by browser.
function processing_instruction($inParser, $inTarget, $inCode) {
if ($inTarget === 'php') {
eval($inCode);
}
}
"If eval() is the answer, you're almost certainly asking the wrong question."
-Rasmus Lerdorf, BDFL of PHP
Is the code you are running so varied that it can't be decided upon as a series of files to be included on demand or a XML-RPC style function call? There is generally very little to gain by allowing arbitrary code execution, and that's before you consider the staggering amount you stand to lose.
If there is a finite, predictable number of things these files could possibly do, I would Strongly recommend taking the time to create a semi-generic XML-RPC interface (or at least a series of files that you could specify in the XML file and then include on-the-fly, perhaps after setting some environment variables, depending on your coding style) and using that.
The number of risks you take when creating a portal to eval() are nigh innumerable.
I had considered providing some examples here, but XML-RPC ought to be a well enough known concept that my doing so is altogether unnecessary.
eval() sadly, is actually the only way to execute it.
UNLESS...
If the code in the XML gets executed more than once. for instance you have a set of 6 Xml files that contain code, kind of like a plugin system.
If that's the case, you can read the code out of the xml, write it out to a .php file, then include that. That would be slower for sure, but if you do that you only have to do it once per XML file. After that you can just run the pure php files.
And, yes like everyone else said, you can't trust untrustworthy code (duh)
For understand the use of "Embedding PHP in XML" see http://code.google.com/p/smallest-php-xml-xsl-framework/
It is a full application with XML+PHP (PHP generating XML) and XSLT as template system. In a MVC architecture the XML+PHP do the "MVC-Model processing" and XSLT the MVC-View.

How do you write good PHP code without the use of a framework?

Other than standard OO concepts, what are some other strategies that allow for producing good, clean PHP code when a framework is not being used?
Remember: MVC, OOP and tiers are design concepts, not language constructs, nor file-structuring.
For me, this means that when not using a framework, and when there's not different teams for programming and designing; there's no value in using another template system on top of PHP (which is a template language). Also, separating code from layout doesn't necessarily mean doing it on different files.
This is how i used to do for one-off, seldom expanded, PHP web apps:
write a 'general utilities' file, there i put some formatting/sanitising functions, as well as a few DB access functions:
getquery(): given a SQL, returns a result object
getrecord(): given a SQL, returns a record object (and closes the query)
getdatum(): given a SQL, returns a single field (and closes the query)
put all configurations (DB access, some URL prefixes, etc) on a 'config.php' file
write a model layer, either one file, or one for each object you store on DB. There, will be all the SQL constants, present a higher-level API, based on your conceptual objects, not on DB records.
that's your 'framework', then you write the 'presentation' layer:
one PHP file for each page, starts with some simple code to fetch the objects needed, followed by HTML with interspeced PHP code, just to 'fill in the holes'. with very few exceptions, the most complex code there should be for loops. I make a rule to use only one-liners, the ?> should be in the same line as the opening <?php
each data-entry form should point to a small PHP without any HTML, that simply get's the POST data, enters into the DB, and forwards to the calling page.
and that's it. If working alone, it has all the separation of intents you need, without drowning in a lot of files for a single user action. Each page as seen by the user is managed by a single PHP file.
It's even easy to maintain, after a few months without looking at the code, since it's easy to test the app, taking note of the filenames in the URL field of the browser. This guides you directly to the relevant code.
(nowadays, of course, i'm using Django for almost everything...)
If you ever find yourself mixing HTML and code, just STOP. You're, well...
You're doing it wrong! http://dennisjudd.com/albums/cute_cats/wrong_mike.jpg
I'd say pretty much the same as for any other language:
Don't optimise prematurely
Keep methods small
Practise DRY
Practise data-driven programming
Use sensible shortcuts (e.g. ternary operator)
Format your code well so that it can be understood by others
Don't use OO blindly
Always check return codes for errors
Enable the highest warning level and ensure your code doesn't produce any warnings
Be very careful when it comes to typing issues (this goes for all weakly-typed languages). The '===' operator is your friend.
Really this question is quite language agnostic, as it applies to most languages where you choose to "roll your own". Two suggestions I would make would be :
Firstly, just because you aren't using a framework doesn't mean you can't adopt the patterns for segregating code. The MVC pattern is the minimum you should consider when arranging you source code - it makes for a much cleaner and easier to maintain collection of source code, even if the application doesn't entirely follow the routing processes associated with frameworks, having code that "does" things separated out from that which "represents" things is very beneficial.
Secondly, just because you've chosen not to use a full framework, doesn't mean you need to reinvent the wheel. Utilise pre-packaged libraries sensibly in order to solve a specific problems. Two good examples would be a logging framework (log4php) and a front-end rendering/templating solution (Smarty).
Stay away from globals as best as possible :-D
If you really do follow OO concepts, like separation of concerns, your code will be pretty good, but here are a few suggestions:
Framework or not, use MVC.
I can't stress enough how important it is to never mix your logic with your HTML. In an HTML file, PHP should be used only as a template language and nothing more.
Use a DBAL.
Separate your design from your content. A common method for doing this is using CSS heavily and having header and footer files containing the bulk of site layout.
Have a single file for option constants, like DB credentials, FTP credentials, etc.
make sure to follow standard practices of separation of concerns. What this means is try not to mix you business and data layer with your UI.
Even If you don't use a framework, use a template engine. By using templates, you'll seperate the logic and presentation of your application. Then design, code and format the logic part like what you would do with any other language. Make the "designers" design the user interface :)
OO is not strictly necessary: it was possible to write good code in PHP < 5 too. Good procedural code, well separated into files and directories by 'logical distance' should also keep you safe. Notice, though, how this starts resembling OO from afar.
Best thing would be to be consistent: I've seen a project where Smarty was used in most pages except one -the most complex, go figure-.
Take advantage of PHP's in-built extensions - MySQLi for example. As these become more object-oriented the requirement for frameworks becomes less.
For example, I could create a useful TwitterApp by using the following extensions and no actual framework besides a core class to tie instances together.
MySQLi for database (PDO if you need DAL)
SimpleXML for RSS/API reading
Smarty for templating
I might need to make a few helper classes for things like Login but my usual pair of classes (DAL and TPL) are made obsolete by two very well worked extensions.

Categories