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
Related
Is the source code of the predefined PHP classes (eg Execption, PDO, etc) available somewhere?
I tried printing the source code of the classes via PHP, but it did not work for predefined classes (probably because the source files don't actually exist on my system?).
The reason why I want the source is that I want to know what and how exactly some methods do what they do (for example, what __wakeup does for PDO).
It's not possible to print out the php source code of those classes as they habe never been written in php. Instead you could have a look at the c sources: https://github.com/php/php-src
If you really want to see the source of the respective classes, I would just go to the php.net website and download the source code of PHP.
There might just as well be that those classes were not even wrote in PHP.
But do you really need to see the source code of those classes?
In case you want to know what __wakeup() does for PDO, shouldn't you rather read the PHP documentation for magic methods ?
It says there
The intended use of __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
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.
Is it inevitable that all php functions will be used sooner or later when developing applications using php? Should only the required functions be learned to complete a project or should all functions be briefly understood before working on programs using php?
The List:
PHP Function List
Also is there a benefit to learning deprecated functions from previous releases of php besides legacy applications?
I have worked quite a bit developing applications using the .NET framework (c#) and found it extremely helpful to understand mainly how the majority of classes work before undertaking a project. Before that it seemed like I was constantly looking back and forth between coding and documentation, and not that we should'nt be reading the documentation but that it takes the fun out of coding when you can't go a statement without looking at the documentation.
Now I have made basic applications using PHP, and the majority of it has been the way I just described. Can I get your thoughts on how functions in PHP should be approached?
It is impossible to learn all functions available in the PHP standard library. Impossible I say.
There are a few handful of functions you'll need every day, and you'll discover them rather quickly and learn them by heart simply by using them. Beyond that there are hundreds of specialized functions you'll need every once in a while, depending on the project. You'll probably need to look up their specifics whenever you need them. Beyond that there are thousands upon thousands of functions you'll rarely need, if ever. You'll need to be able to find those when the need arises, but not any sooner.
The best way is to keep the manual close at hand and search it whenever you think "there should be a function for that". You'll do this a lot in the beginning and less often later on.
Feel free to skim the manual for function groups, you may discover that there are functions for stuff you didn't even know you could do. That may be valuable knowledge some day. Do not try to memorize everything in detail though. It won't stick anyway and only bore you to tears.
It should be approached as with any other language - you try to code something, get stuck, look up the docs if you find something related to your problem and use that. Otherwise you extend your research. There is no need to learn everything and anything. Personally, I don't see the point of reading about all functions simply to have read of them. Why should I, if I don't need them? Even though this is not coding directly, YAGNI (you ain't gonna need it) applies here as well. Learn about the functions when the need arises, not simply because you can.
IMHO, you should understand what certain function does rather then how it is doing it.. Obviously there are exceptions of functions that are similar (i.e. str_replace vs preg_replace or print vs echo - mostly string functions) and knowing how they work might give you an insight of performance.
Learning ALL php functions is not really necessary as you will not need them in everyday coding. You'll learn as you go (e.g. you need to manipulate and array; then you go and read all PHP array function and see if any suits the need for your problem. rather then doing it another way around. learning all php functions and start coding)
I can only support th answers given...
It is more or less impossible because there are a lot of functions, and when you have learned all the function there are functions you do not know they exist.
You have no big benefit comparing to the time you need to learn them. All important functions you will use every day and so learn them by using them.
Every day there are new libraries, or new versions of existing and useful libraries, every day some other programmer writes a new function and post this function in one of the millions pages on the web.
When you need some special funciton, you will use the manual, or if it is some exotic function use google. And when there are no solution for you problem, you will code som own funcitons and libraries and use them instead of functions in the manual or other libraries...
So I think that are some of plenty reasons not to learn all php functions...
Of course not.
Only string manipulation ones.
Dunno where did you get that list. It's totally useless. Not list but structured reference is what you really need.
Just take a brief tour on manual sections to picture yourself list of PHP features, so, you'll know where to look on occasion.
Only string manipulation functions deserve closer look, just because PHP itself is mainly string manipulation language.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
ok, I'm relatively new to PHP programming and have been plodding along quite unaware that it is possible to actually use namespaces in PHP as I can in c# etc.
It's really ugly though as they have decided to use backslashes - why!?
Anyway, I am interested in other PHP programmers' views on whether namespaces will catch on in PHP and whether I should begin to use them now?
Here are some solution attempts for those wondering about name space functionality, without php 5.3.
First, I must say, only prefixing worked for me, the other solutions below are sort of notes not to go that way.
Namespace functionality can be needed if, for example, one produces wordpress plugins, using your valued function library in them. Normally you cannot have multiple plugins with function declarations of same functions, it would cause fatal errors.
SOLUTION 1: prefix all your library functions with plugin_name_ or namespace_
function str_len_utf8($str)
becomes
function photoplugin_str_len_utf8($str)
Is just a matter of find-replace. Easy if the functions are already prefixed uniquely:
john_str_len_utf8() => photoplugin_john_str_len_utf8()
Good for the soul as well, supports the ego, 'johns string library' :D
If you choose short and nice prefixes with some common sense, it works like a charm, as they say.
SOLUTION 2: enclose all your library/reeuse functions in a class.
class photopluginlib
{
function str_len_utf8($a){ $a=$this->str_clean_utf8($a); ...}
...
}
All function calls in the class to the class are prefixed with $this->. Once this class is prepared, one can use it repeatedly without search-replace, changing the classname is enough. Usage:
$photopluginlib=new photopluginlibrary();
$b=$photopluginlib->str_len_utf8($a);
SOLUTION 3: enclose all your library/reeuse functions in a class, and use :: operator
class photopluginlib
{
static function str_len_utf8($a){ $a=self::str_clean_utf8($a); ...}
...
}
All function declarations in the class have keyword static in front of function.
All function calls inside the class to the class are prefixed with self::
Once this class is prepared, one can use it without search-replace. The class name is the namespace, sort of. One only changes the class name and uses it as such.
$b=photopluginlib::str_len_utf8($a);
$c=photopluginlib::database_row(...)
No need to instantiate the class.
Looks nicer than $photopluginlib->str_len_utf8(), but I still prefer photoplugin_john_str_len_utf8()
Notes
all libraries need to go into 1 big library class declaration, you practically cannot add methods to classes later in php.
you cannot just declare new library functions here and there in different php files.
if multiple libraries are used, and they are using each other, they need to use self:: for function calls.
php5.2.17, common 2013, does not accept call_user_func('photopluginlib::functionname'), need to use call_user_func(Array('photopluginlib','functionname')) or inside class, call_user_func(Array(__CLASS__,'functionname')), which means code rewrite for wp add_action, preg_replace_callback etc.
needs php>=5
cannot mix code and function declarations, as in:
class photopluginlib{ add_filter('html','myfilter'); static function myfilter($html){return ''} }
For big code, it can quickly become a big complicated mind bender.
I prefer to just use prefixing until the real thing, namespaces, are widely available.
These solutions still mean one has to prefix all function uses. Namespace functionality would mean one can use functions without prefixing them, the prefix would be just once, at begin of the php file:
<?php
namespace photoplugin;
...
$b=str_len_utf8($a);
By the way, upgrading to php5.3 has an additional advantage, if you can choose not to code for php5.2 (still everywhere, year 2013) Php5.3 vs php 5.2.17 means instant speed increase. It looks like %30 etc speed increases are available, not considering the database side:
http://onlinephpfunctions.com/benchmarks
Hope this helps inspire some solutions to those reaching for namespaces.
Its use is already catching on. A couple of projects use it in their upcoming/beta versions. Most examples I've seen however use it like a cargo cult. Doctrine2 for example uses five or more nested namespaces (code smell), probably to provide a 1:1 mapping of namespace/class to the filesystem/directories. I guess the novelty makes PHP namespaces prone to unreasoned overuse.
Anyway, the syntax doesn't help with readability that much. And it's a big turn off for professional programmers. But if there is a serious use case in your project, just go for it. (Hypothetical naming conflicts are not the best reason.)
They will most likely not catch on until the core starts using them (in PHP 7 maybe possibly perhaps...), but using Python for a few months will show you that namespaces are AWESOME.
Unless all your code runs on your own servers, it's too early to start using them as 5.3 is relatively new.
Other than that, I'm not sure if they will ever really catch on. Even classes took a long time to catch on with a large portion of the PHP programming population.
I would start learning how to use namespaces as soon as possible. Zend Framework 2.0 will use namespaces, which will mean that anyone using PHP 5.2 or lower will be out of luck. I use a virtual dedicated server, so I can control my PHP version. If you use cPanel/WHM, you can install PHP 5.3 very easily. If you are on shared hosting, it may be a little bit before you see 5.3 installed, although there are 5.3 adopters out there.
Namespace is not needing for PHP.
For example, in C# and Java, it is usual to use several libraries (specially standard one) and each libraries contain thousand of classes and definitions for each library. So, the chance of a conflict is high.
Instead, in PHP is different, we don't need to load several libraries, at most a framework plus some separates .php files. How PHP works discourage to loads biggest libraries but to use a bare minimum. It is why the chance of a name conflict is pretty dim. Also, frameworks are seasoned to use a short prefix, for example Wp_User (Wordpress).
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.