Three string functions every PHP project needs
engineering.thumbtack.com
engineering.thumbtack.com
https://github.com/Nycto/Round-Eights/blob/master/src/functi...
It could be a micro-optimization, but I find myself using these methods quite and it's a simple tweak to make.
In general though we just use these around the code base for general use, and efficiency isn't a concern.
Surely a singleton class would be a nicer way to do this (or just leave the "tt_" off, why is it necessary, you're not overriding core functions)?
We decided against putting them in explicit namespaces, because we felt these were convenience functions and they should be convenient to use. We felt the convenience of:
if (tt_str_startswith($url, 'https://)) { }
over something like:
if (tt/global/string/starts_with($url, 'https://)) { }
was worth the lack of organization. We have <10 of these types of global functions in our code base and we are very careful about adding new ones. All other classes and functions are either in a namespace or class context.
We went with the tt_ prefix because we wanted to cover our bases and really explicitly ensure we never will collide with a PHP function, and we felt it isn't too unwieldy.
As for using a singleton class, since 5.3 we prefer to use namespaces instead.
use tt\global\string;
if (string\starts_with($url, 'https://)) { }However in this context again we felt that the convenience of just being able to throw these functions in place without having to worry about putting the proper use statement was worth the tradeoff.
String.prototype.startsWith = function(s) {
return this.substring(0,s.length)===s;
};
String.prototype.endsWith = function(s) {
return this.substring(this.length-s.length)===s;
};[1] http://michaux.ca/articles/javascript-the-good-parts-built-i...
There's also visibility concerns. If you add random methods to things that look like language primitives it can be hard to get an overview of where they're really being used.
Anecdotally, I had to go through and remove all use of prototype.js from deviantART because we decided to standardize on jQuery. It was a pain. A serious, serious pain. Because prototype.js extended Array, String, and other objects. So I had to go make a list of every single method that prototype.js added to these, and find all incidences of those somewhat-common strings in our codebase and examine them case-by-case to see if they were actually calling the prototype.js versions.
By contrast, if I'd wanted to remove all use of jQuery I could have built an unambiguous list of all uses with a fairly simple grep.
Also, wouldn't startsWith and endsWith also be already implemented as strpos and strrpos?
Don't get me wrong, none of those functions are particularly elegant, but at least they are the "PHP way".