What PHP 5.5 might look like
nikic.github.com
nikic.github.com
$names = array_column($users, 'name');
// is the same as
$names = [foreach ($users as $user) yield $user['name']];
The only possible reason would be due to a significant speed difference, but I'd suggest improving the efficiency of the list comprehension system (even if just for common cases) than adding more functions.As opposed to the introduction of list comprehensions, I can't say I like the solution for parameter skipping though... I disagree with the author -- many optional arguments is not a problem, but only if keyword arguments or a similar style are used. Consider the example they give:
// This create query function in PHP
create_query("deleted=0", "name", default, default, false);
// could be represented like this with keyword arguments
create_query("deleted=0", "name", escape_arguments=false)
I tend to find keyword arguments serve the purpose of self documentation as well -- I still have no clue what the false flag would be for the PHP create_query statement.Keyword arguments and many optional arguments can allow for beautiful and flexible functions, such as the Python Requests library[1].
r = requests.get('https://api.github.com/xyz')
# or we could add a few more complications
# -- no "defaults" in sight and also self documenting
r = requests.get('https://api.github.com/xyz',
auth=('user', 'pass'), timeout=0.5, allow_redirects=True)
[1]: http://docs.python-requests.org/Isn't the function call much more readable than the comprehension?
At least as a beginner, I found the large set of built in functions to be one of the strongest points of PHP.
As far as list comprehensions, I tend to find list comprehensions the readable and self documenting, at least in Python where I most commonly see them. If nothing else, what is the ordering of the arguments for the equivalent non list comprehension? With list comprehensions you don't have that impedance.
// Python example with filter vs list comprehension
// Filter requires you to remember the ordering --
// and does it filter on True or False?
filter(lambda x: x % 2 == 0, range(10)) --> 0 2 4 6 8
// The list comprehension is self documenting
[x for x in range(10) if x % 2 == 0] --> 0 2 4 6 8
I can also convert the majority of list comprehensions into English quite easily -- "output x for each x in range(10) if x is divisible by 2" (though it may be cleaner if it was "for each x in range(10) [output x] if x is divisible by 2").[1]: http://php.net/quickref.php
[2]: http://docs.python.org/library/functions.html + http://docs.python.org/library/exceptions.html
They could do what Python did for 3.0, and make a tool similar to Python's 2to3 that replaces global namespace references.
With regards to the array_column function, PHP has a history of providing such functions for common operations, even where the same functionality can be replicated with more generic code constructs. For me, the function example you provide is more readable than the comprehension example, requires less typing and provides less room for mistakes. I.E. its simpler in this case, and that’s part of the way PHP rolls. There is of course an argument that functions like this should be provided by external libraries or frameworks rather than in the core of the language, but that debate has been had many times and PHP has come down on the side of including them. This is one of the reasons developers like me like PHP. YMMV.
$options = ['timeout' => 0.5];
$r = Requests::get('https://api.github.com/', $headers, $data, $options);
[1]: http://requests.ryanmccue.info/IMO This is a problem and bad design, because instead of default arguments you can use properties for optional arguments.
Err... what? You want map, use map.
Right now this is how I do this:
function salute($user, array $options = null) {
$options = (array) $options + array('shout' => false);
$salutation = "Hi $user!";
if ($options['shout']) $salutation = strtoupper($salutation);
return $salutation;
}About the rest of the article :
- the modified empty() is nice, while I still think this function accepts to much thing as empty, or at least should be more flexible.
Getter/setter : finally. Now I don't get why there is no readonly keyword which would put the variable as readonly only for the class' outer world.
https://wiki.php.net/rfc/propertygetsetsyntax-as-implemented
class Foo {
private $fuzz;
protected $Bar {
get { return $this->fuzz; }
private set { $this->fuzz = $value; }
}
}My point was just that he specifically wanted a read-only.
The explanation, a bit further down in the eRFC is that the function password_hash doesn't actually return a password hash, but a string including the algorithm and options used, the salt and the hash itself.
From the RFC:
> It's important to note that the output of crypt() (and hence password_hash()) contains all the information that will be needed to verify the hash later. Therefore, if the default hashing algorithm changes, or the user changes their algorithm, old hashed passwords would still continue to function and will be validated properly.
Given the recent threads about planned obsolescence (Apple) and OS fragmentation (Android) I'm curious what is missing from XP/2003 that is part of Vista+. Are there still exciting things happening in the world of OS APIs that are relevant for server software?
Or does this just mean that noone will actively test the binaries on XP anymore?
It was nice to see short tags "<?" coming back in 5.4. Before that, they used to say, don't use short tags, it's dangerous, breaks things. But users resisted it, and every ISP kept it open. And now from PHP 5.4 short tag is ON, regardless of whether one setts it On or Off in php.ini.
https://connect.microsoft.com/VisualStudio/feedback/details/...
https://connect.microsoft.com/VisualStudio/feedback/details/...
The VS2012 MSVCRT will not run on XP initially, but a post-RTM patch to bring XP support back was mentioned on the VS blog[1]. So that would only prevent XP support between the VS2012 release and the post-RTM patch, and only if the PHP team upgraded at the first chance.
[1]: http://blogs.msdn.com/b/visualstudio/archive/2012/05/18/a-lo...
However, what I'd really like to see in next PHP would be the Composer dependency manager bundled in, a bit like Node.js nowadays ships with NPM. This has really brought a new world of cross-project code sharing into PHP:
I wrote a blog post on why this is important for improving the state of PHP:
http://bergie.iki.fi/blog/composer_solves_the_php_code-shari...
Awesome work Nikita, keep it up!
So very much agree, keep it up!
Kudos.
[1] oh look, I'm still mentioned in the RFC :) - https://wiki.php.net/rfc/scalar_type_hinting_with_cast
To start, you can consider the problem of type checking of scalars in a language with implicit type coercions. You're supposed to be able to treat 0 and 0.0 the same. At the same time, if you have a type check that says "int", you kinda expect to get an int. So "with cast" does that.
I know a lot of people find that ugly, and that you want to strictly that you must receive an int, but that's just not how people use PHP, and it doesn't make sense in the context of the language. As an example, you want to be able to add type checks to all the functions in the standard library, many of whom treat null, "0", 0 and 0.0 to be the same.
For PHP specifically, there is the additional consideration that PHP is supposed to be a newbie friendly language. There was a perception in the PHP internals community that newbie developers could not wrap their head around the concept of "types". I've heard people say that a developer shouldn't be required to think about what types his variable might hold. Clearly this is lunacy for many reasons, but there it is.
I regularly check the bug tracker and I haven't noticed any special aggressiveness - of course, some of the volunteers may sometime be impatient, especially with newbies, or trolls, some of which lately for some reason decided it is appropriate to publish their "php sucks" diatribes on the bugtracker - but I didn't notice any systematic aggressiveness. Some data would be helpful here - demonstrating the problem may be necessary for fixing it.
Same for regard for other members of the community. Various members of the community regularly participate in the discussions, and once PHP moved to git they also submit pulls, rfc, etc. Yet still you describe the situation as "complete disregard" - so what you would say should be happening instead?
I think there might be some Stockholm Syndrome there. The volunteers in the PHP bug tracker are dicks! Or were, it's been 3 years so things may have changed. And I'm not talking about responses to trolls, I mean to ordinary users.
I mean they disregard the feelings of the other people in the community, not their code. I'm not really talking about how dysfunctional the coding practices were, I mean the actual community dynamics. It felt a lot like trolls feeding trolls.
I've spent major time in 3 open source projects, gcc, Mozilla and PHP. All of them suffered from similar disagreement, from old code, from old decisions they need to move away from. The difference was that Mozilla and gcc manage to do it without being poisonous.
Look at it this way - imagine you had a conversation with a group of people 4 years ago, and they acted like dicks. Now, four years later someone challenges you to explain how they were dicks. It's really hard to give an answer better than "i dont know, they were just dicks alright" :(
function create_query($where, $order_by, $join_type='', $execute = false, $report_errors = true) { ... }
create_query("deleted=0", "name", report_errors: true);
can even specify all parameters by name in different order create_query(order_by: "name", report_errors: true, where: "deleted=0");The bit about getting the fully qualified class name is important, but it still prevents you from doing something like:
function builder_factory( $var ) {
$class = $some_array[ $var ];
return new $class();
}
So you have to write a ton of boilerplate for something that used to be easy without namespaces, or write namespace traversal into your PHP (which isn't THAT hard, but is very ugly).Parameter skipping looks intuitive and useful. Very important as we incorporate more functional paradigms into the code.
I don't believe scalar type hinting will make it in. There's just too much discussion around it. IMHO, it should be super strict. "1" is not an integer.
Getters and setters: meh. I guess it's good. Better than what we have now.
I don't believe PHP will do generators or list comprehensions right, so I'm not holding my breath on those.
http://stackoverflow.com/questions/410002/fixing-the-php-emp...
The behavior of empty is unreliable. isset is not ambiguous.
Ultimately this isn't a language issue, it's a training issue. If you're using empty in place of isset, you're doing it wrong, the both serve completely different purposes.
function foo($a, $b="10", $c="5", $d="3") { /* .. */ }
foo(5, $c="10");
That way $a == 5, $b == "10", $c == "10", and $d == "3". Much better and cleaner syntax in my opinion and a lot of other languages support something similar. function foo($a, $b = "10", $c = "20") {}
foo(1, $c=20);
var_dump($c); // int(20)
The syntax would have to be unambiguous. Perhaps: foo(5, c: 30)
or foo(5, $c: 30);
or foo(5, $c => 30)
or something like that...I'm still looking for a good way to combine array parameters with defaults and hinting in PHP 5.3. I've had some success using DTO's for primary API's:
function foo(SomeDTO $data) { ... }
foo(new SomeDTO(array("a" => "foo", "b" => 10)));
class SomeDTO extends BaseDTO {
/** @var string
@maxlength 10 */
public var $a;
/** @var int */
public var $b = 20;
}
The BaseDTO class uses reflection to parse the doc comments and figure out how to validate and set its input. It's the same idea as validation annotations in java. It works, but it's quite a heavy syntax, and I wish I had a lighter-weight alternative. I like PHP's loose typing inside an API's class, but when interfacing between API's I want strict typing.The author says this about parameter skipping:
Personally I’m not particular fond of this proposal.
In my eyes code that needs this feature is just badly
designed. Functions shouldn’t have 12 optional parameters.
I'm not fond of this proposal either, for it doesn't solve a problem named parameters do, which is that sometimes function parameters don't have a logical order, and cramming them into an array feel sloppy as hell.The problem with PHP is that, due to the nature of the interpreter, so many of these things are written as syntactical sugar which means that their implementations usually leave much to be desired.
There's nothing functional to skipping parameters, as far as I know. None of the functional languages I've used supports such a concept, nor would it make sense in most of them.
I'm not sure if the list comprehensions feature has made it past the mailing list though.
The default value for method arguments is a shockingly bad idea for a new feature, it only supports the old, bashed upon, code quality that have been PHPs greatest legacy problem. If anything in this alley I'd like to see named arguments somehow.
I'm not so sure about property getter/setters as I find the syntax a bit awkward, all while magic methods lets you create getter/setter based APIs.
Also I'd prefer it to support scrypt as well as bcrypt.
Considering:
* no password hash algorithm I know of supports peppers
* that the API allows providing a custom salt
I don't see any issue with the API. If the cryptographic worth of peppers is ever demonstrated and a password hash is built to use peppers, the pepper can be provided as an option to that hash algorithm as the salt and cost already are in the proposed API.
The problem with this API is that if you pass in the "salt" as $salt.$pepper then the output hash also contains the pepper.
The whole point of a pepper is to keep a second salt out of the database. The user salt would be in the database, but the pepper should only be in the application code.
If your database is stolen, but your application code is safe the pepper increases the complexity of brute forcing, as they need to work out what the pepper is
1) this wrapper can be applied to any hash scheme, regardless of it's internal structure or options.
2) it doesn't expose the pepper within the hash string.
3) brute-forcing the hash w/o the pepper means you're searching for the 64-byte binary string returned by hmac_sha512. whereas (assuming all inputs are ASCII) "md5(salt+pepper+password)" can still be brute-forced, just treat the pepper as part of the password you're looking for.
That is not the meaning I intended in my usage of the word "support", but if you equate "support" and "is compatible with", then this API also "supports" peppers, just as much as bcrypt does.
> md5($salt.$pepper.$clearText)
How cute, not just md5 but length-extension vulnerable MD5. I'd recommend not using that scheme for MACs (and more generally not using md5 directly, really, as there are precious few reasons to do so)
> The problem with this API is that if you pass in the "salt" as $salt.$pepper then the output hash also contains the pepper.
Which just happens to be the exact same way bcrypt's API works. Here's an idea: combine the pepper to the password (this is usually done through hmac), not the salt. That's how you use a pepper and remain compatible with the Modular Crypt Format.
> The whole point of a pepper is to keep a second salt out of the database [blah blah blah]
Contrary to your apparent belief, I am aware of what peppers are, how they are used and what they're supposed to do.
One reason it is like that has to do with string interpolation. PHP interpolates $x[0] inside double quotes, but does not (and probably should not) interpolate [0][0]. I am not saying this is a good solution, but hopefully that answers "how is that even possible?" question.
PHP enforces a lot of things in the parser (as opposed to making bytecode and having a simple type checker). Instead of having a general "expression" type which can be dereferenced, they have different rules for scalars, strings, variables, function calls, etc. For a long time, you couldn't dereference the result of a function call, because the parser didn't allow it, so this is probably the same.
$foo->getBar()->getBaz()
If getBar() return NULL for some reason, you get a fatal error which you cannot catch and handle without reverting to uglu hacks with a shutdown function.My personal preference would be to have that statement return NULL and raise a warning or notice, alike to using uninitialized variables.
array_copy()
... in order to copy-by-value on arrays containing references. Currently to do that you have to do a very fragile hack like this: $copy = array_flip(array_flip($original));
... which is vulnerable to key-value collisions ... or you have to write your own homebrew array copy-by-value function. $copy = array_map( function($v) { return $v; }, $original );Either:
$copy = $original;
Or, if you must have a function, function array_copy(array $a) {
return $a;
}
Arrays use the normal copy-on-write semantics of PHP. They are not passed by reference or object handle...The only potential issue is if the array contains references deeper in.
Deleted comment
No, I don't have a dire need. But almost no one has a dire need.
I'm not sure if you're serious, but there are plenty of frameworks on a par with Rails at least (nb: I have zero experience with Django).
At the enterprise level, there's Symfony or Zend:
If Rails is your thing, CakePHP shares some concepts (although I'll be the first to admit CakePHP has many flaws):
Want something lightweight that's easy to jump into? CodeIgniter's the one for you!
And finally, my favourite, Kohana. Absolutely infuriating since they essentially stopped writing documentation for new versions, but if I need to get something written quickly and reliably, this is my go-to call:
There are tonnes of "serious" frameworks for PHP (I've certainly missed out a few), and frankly, if you're going to try to attack PHP, this is the wrong angle from which to do so.
CI is not Zend, but nothing prevents you from using the Zend libraries with a small CI Library wrapper - I have done so many times in the past, and it works great.
We had issues where the router and loader were not playing nicely at all - we were using the 404 override option in order to do some custom routing (as the router was not flexible enough for even a very basic CMS). However because of how messy the routing code is, and how much of a hack the 404 override was (last time I checked there were several open bugs regarding this on their tracker, some over a year old and completely untouched), it completely blitzed the loaded libraries, so we had to add in more hacks to dodgily clear the cache of loaded libraries and re-run the loader in order to have them available. The only other way to do this would have been to modify the core loader to fix the bug there (but we didn't want to modify core code to make it easier to keep up to date with framework changes), or completely rewrite the router (which really needs to be done, it's a mess).
The database abstraction code is very kludgy and basically useless for anything beyond utterly, utterly basic use cases (there's a reason it's low overhead - it's low everything, including functionality!)
That's just a few of the things we ran into. By the time we went to production I estimate that out of the maybe 30% of CodeIgniter we were actually using for our project, I had re-implemented as custom libraries maybe a third of that amount just to get some sane behaviour, and work around long-standing bugs. Overall I got the feeling that the framework had no solid direction, some of the core components (most critically the loader and router) were quite obviously piles of hacks rather than having been designed and engineered, and honestly the framework was not really much more re-usable or robust than our own custom in-house one. I know it's a very common developer hubris to think you could write your own framework and do a better job, but in the case of CodeIgniter I can confidently make that claim.
On the more technical and abstract side, it's insane that it doesn't use standard PSR loading (so any other library you want to use you have to write a custom wrapper), and the guidance on making re-usable libraries / modules / packages (I can't even remember the right terminology, they use these words in strange ways) is... unclear at best. It uses globals, it's tightly coupled, everything a decent framework should categorically not be. Overall I would say that the level of technical ability on people using and contributing to CI is very low, and most people I've spoken to that think it's great haven't actually used any other framework (which is, frankly, endemic of a large portion of the PHP-using world)
Edit: Also if you care about overhead, you're not writing what I would call a small to medium sized application! Any framework out there worth its salt (and many that are not) will be able to run your application just fine, it's extremely unlikely that the PHP layer will be the bottleneck unless you're writing really terrible code or using a really terrible framework.
I wouldn't have a few years ago, but the current version seems decent enough. Out of interest, what're your main complaints with it?
I'm not a huge fan of CI, but would prefer it to my personal bugbear, CakePHP.
> frameworks that were built with PHP 5.3 in mind.
Well no crap, CodeIgniter is built for newbies in mind, people who don't have up to date PHP installs because their shared hosting doesn't keep it THAT up to date.
The newest versions of CodeIgniter are VERY good, and just like the haters of PHP, you're just hating on versions of CodeIgniter that are at least 3 versions old. Learn the updated system, then base your claims on that, not something you looked at 2+ years ago.
Your point about PHP versions isn't very valid. 5.3 is over 3 years old now! Plenty of cheap hosts are far more up to date than that.
There is a difference between being "newbie friendly" (which I will admit, CI is - it's a lot easier to get into than say, Zend, by orders of magnitude) and "enabling bad practices". You could say that using mysqli and concatenating data into your queries is newbie friendly, and it is - it's a lot simpler conceptually than prepared statements, but that doesn't stop it being categorically a bad idea.
For the record my CI experience ended about 9 months ago, and I have contributed code to CI, so I feel that when I say certain parts of the internals are very badly coded I do have some valid perspective on that issue.
Also, the next version is supposed to redo the ORM to return actual models.
I think you meant the comparison as insulting, but it actually isn't. You're saying PHP is a T-Rex of web development. It's a nice compliment :)
Drupal is an odd duck - it's a framework with a built in CMS. It's immensely powerful for many developers who put the time in to learn it, but the experience is often jarring for traditional "object oriented" developers so they come away with a bad taste in their mouth: "no objects? this is icky!"
Of all the major PHP projects, Drupal seems to be the one embracing good software architecture - Drupal 8 looks to be amazing. It's come a long way from the days of Drupal 5.
I can't speak for Drupal or Magento, but WordPress's codebase is a world of pain. I've written a few plugins in the past, and the WordPress code is simply hell to work with.
Magento is on a whole other level of suck. I worked on a highly customized Magento site 3 years ago, and it was the worst experience of my professional career - lousy software and client-from-hades.
The Magento folder structure is just completely insane...some of the templates are like 8 or 9 subfolders deep, and it's the huge mashed up pile of Zend Framework and homegrown MVC, none of which is well documented (Since after all, they want to push you to paid support...)
Oh, and to further cement the suck, the main database tables are in EAV form. Tons of fun to be had.