154 points · by nikic · 14y ago · 133 comments
$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
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?
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
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.
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.
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.
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.