phpundmysql.de

Archiv der Kategorie ‘PHP’

Gehversuche mit OAuth

Montag, März 19th, 2012

PHP 5.4 erschienen

Donnerstag, März 1st, 2012

NicEdit im Admin-Panel von Wordpress nutzen

Montag, Oktober 31st, 2011

Im Folgenden zeigen wir am Beispiel eines eigenen Theme Options Menü, wie man die darin enthaltenen Textfelder mit einem WYSIWYG Editor ausstatten kann - wie etwa nicEdit. Das Vorgehen lässt sich auf beliebige andere Editoren übertragen; wir haben nicEdit ausgewählt, weil das Leichtgewicht außer seinem JavaScript Code nur eine einzige Bild-Datei mitbringt.

Als Basis dient uns eine Theme Option Seite von ThemeShaper, dazu laden wir uns die aktuelle komprimierte und ausgeschlachtete Version des WYSIWYG Editors herunter. Wir benötigen hier nur die Standardfunktionen, was unser entstehendes JavaScript auf 20KB zusammendampft. Die theme_options.php legen wir wie im Artikel von ThemeShaper beschrieben in das Hauptverzeichnis unseres Themes, die Datei nicEdit.js kommt mitsamt der dazugehörigen Grafikdatei (nicEditorIcons.gif) in dessen Unterordner js.

Abschließend müssen wir an beiden neuen Dateien Hand anlegen, und zwar verändern wir die theme_options.php und erweitern die minified nicEdit.js. In den theme_options wird aus

function theme_options_add_page() {
	add_theme_page( __( 'Theme Options', 'sampletheme' ), __( 'Theme Options', 'sampletheme' ), 'edit_theme_options', 'theme_options', 'theme_options_do_page' );
}

das erweiterte Codestück

function theme_options_add_page() {
	global $theme_options_hook;
	$theme_options_hook = add_theme_page( __( 'Theme Options', 'sampletheme' ), __( 'Theme Options', 'sampletheme' ), 'edit_theme_options', 'theme_options', 'theme_options_do_page' );
	add_action( "load-{$theme_options_hook}", 'theme_options_enqueue_script' );
}
 
function theme_options_enqueue_script() {
    wp_enqueue_script('theme_options_nicedit', get_template_directory_uri() . '/js/nicEdit.js', array('jquery'));
}

Wir definieren eine globale Variable und weisen den Wert von add_theme_page zu. Dadurch erzeugen wir einen neuen Hook, den wir mit der Funktion add_action ansprechen können. Als Konsequenz wird bei jedem Aufruf der theme_options.php die Funktion theme_options_enqueue_script ausgeführt und die Datei nicEdit.js eingebunden. Bitte nicht vergessen, de Aufruf der theme_options.php in die functions.php des Themes einzutragen (siehe den originalen Artikel von ThemeShaper).
NicEdit hat zwar selbst keine Abhängigkeiten zu jQuery, wir definieren sie in wp_enqueue_script aber dennoch, weil die kommenden Anpassungen in der nicEdit.js darauf beruhen.

Was es in der JavaScript-Datei von nicEdit noch zu erweitern gilt, ist die Instanzierung des Editors und die Übergabe des Pfades zur Icon-Datei. Wir fügen also an das Ende der Datei in einer neuen Zeile folgendes hinzu:

jQuery(function() {
	var path = jQuery('script[src*="nicEdit.js"]').attr('src');
	new nicEditor({iconsPath : path.substr(0, path.lastIndexOf('/')) + '/nicEditorIcons.gif'}).panelInstance('sample_theme_options[sometextarea]');
});

Wichtig ist, dass wir in der neuen Instanz den Pfad zu den Icons mittels iconsPath setzen. Diese Datei soll aus demselben Verzeichnis geladen werden wir die nicEdit.js. Weil der Pfad zum Javascript Verzeichnis des Themes aber nicht so einfach aus der aktuellen URL auszulesen ist, bemühen wir jQuery, um uns den Pfad zur nicEdit.js aus dem DOM herauszusuchen, in der Variable path zu speichern und danach aus demselben Verzeichnis (path.lastIndexOf('/')) die Bilddatei nachzuladen.

Damit erhalten wir das gewünschte Ergebnis:

Google+ API für PHP

Sonntag, September 11th, 2011

Natürlich gibt Striegel zu bedenken, dass es sich nur um eine vorläufige Version handeln kann - da sich Google+ noch in der Entwicklung befinde, können sich die Strukturen jederzeit ändern. Wie aber kann ein Entwickler, der an der Implementierung des sozialen Netzwerkes nicht beteiligt ist, ein API veröffentlichen? Nun, die Schnittstellen basieren auf den öffentlichen Informationen, nämlich den Personen, deren Verbindungen und öffentlichen Posts.

Ein Grundstock also, mit dem man erst einmal probehalber arbeiten kann. So lassen sich vielleicht auch die Monate überbrücken, bis Google nachzieht. Jasons Schnittstelle liegt bei Github. Wer sich für das Developer Program von Google+ interessiert, kann sich in eine Liste eintragen, über die man über Neuigkeiten informiert wird - zu viel Offnheit sollte man hier nicht erwarten: über zwei Monate lang kam hier keine einzige Nachricht.

40 Tips zur PHP Optimierung

Freitag, August 12th, 2011

Wie das im Netz so ist: der ursprüngliche Link zum Artikel existiert nicht mehr (reinholdweber.com hat bei seiner Blog-Aktualisierung sämtliche alte Posts weggeworfen), aber es gibt reichlich Repliken davon - vielleicht ist der eigentliche Autor auch ein ganz anderer. Jetzt ist es ein Repost mehr. Die Aussagen sind von unserer Seite nicht getestet. Speziell mit Faktoraussagen muss man vorsichtig sein, auch weil die Liste nicht in allen Punkten aktuell ist:

1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
2. echo is faster than print.
3. Set the maxvalue for your for-loops before and not in the loop.
4. Unset your variables to free memory, especially large arrays.
5. Avoid magic like __get, __set, __autoload
6. require_once() is expensive
7. Use full paths in includes and requires, less time spent on resolving the OS paths.
8. If you need to find out the time when the script started executing, $_SERVER['REQUEST_TIME'] is preferred to time()
9. See if you can use strncasecmp, strpbrk and stripos instead of regex
10. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4
11. If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
12. Error suppression with @ is very slow.
13. $row['id'] is 7 times faster than $row[id]
14. Error messages are expensive
15. Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
16. Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
17. Incrementing a global variable is 2 times slow than a local var.
18. Incrementing a object property (eg. $this->prop++) is 3 times slower than a local variable.
19. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
20. Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
21. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
22. Methods in derived classes run faster than ones defined in the base class.
23. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
24. Surrounding your string by ' instead of " will make things interpret a little faster since php looks for variables inside "..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string.
25. When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.
26. A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
27. Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.
28. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load
29. Use ip2long() and long2ip() to store IP addresses as integers instead of strings in a database. This will reduce the storage space by almost a factor of four (15 bytes for char(15) vs. 4 bytes for the integer), make it easier to calculate whether a certain address falls within a range, and speed-up searches and sorts (sometimes by quite a bit).
30. Partially validate email addresses by checking that the domain name exists with checkdnsrr(). This built-in function checks to ensure that a specified domain name resolves to an IP address. A simple user-defined function that builds on checkdnsrr() to partially valid email addresses can be found in the user comments section in the PHP docs. This is handy for catching those occasional folks who think their email address is 'joeuser@wwwphp.net' instead of 'joeuser@php.net'.
31. If you're using PHP 5 with MySQL 4.1 or above, consider ditching the mysql_* functions for the improved mysqli_* functions. One nice feature is that you can use prepared statements, which may speed up queries if you maintain a database-intensive website. Some benchmarks.
32. Learn to love the ternary operator.
33. If you get the feeling that you might be reinventing the wheel during a project, check PEAR before you write another line. PEAR is a great resource that many PHP developers are aware of, yet many more are not. It's an online repository containing over 400 reusable snippets that can be dropped right into your PHP application. Unless your project is trully unique, you ought to be able to find a PEAR package that saves at least a little time. (Also see PECL)
34. Automatically print a nicely formatted copy of a page's source code with highlight_file().This function is handy for when you need to ask for some assistance with a script in a messageboard, IRC, etc. Obviously, some care must be taken not to accidently show your source when it contains DB connection information, passwords, etc.
35. Prevent potentially sensitive error messages from being shown to users with the error_reporting(0) function. Ideally error reporting should be completely disabled on a production server from within php.ini. However if you're on a shared webhost and you aren't given your own php.ini, then your best bet is to add error_reporting(0); as the first line in each of your scripts (or use it with require_once().) This will prevent potentially sensitive SQL queries and path names from being displayed if things go awry.
36. Use gzcompress() and gzuncompress() to transparently compress/decompress large strings before storing them in a database. These built-in functions use the gzip algorithm and can compress plaintext up to 90%. I use these functions almost everytime I read/write to a BLOB field within PHP. The only exception is when I need full text indexing capabilities.
37. Return multiple values from a function with 'by reference' parameters. Like the ternary operator, most PHP developers who come from a more formalized programming background already know this one. However, those whose background is more HTML than Pascal, probably have wondered at one time "how do I get multiple values back from a function I wrote, even though I can only use one return value?" The answer is that you precede a variable with "&" and use it 'by reference' instead of 'by value'.
38. Fully understand "magic quotes" and the dangers of SQL injection. I'm hoping that most developers reading this are already familiar with SQL injection. However, I list it here because it's absolutely critical to understand. If you've never heard the term before, spend the entire rest of the day googling and reading.
39. When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using a isset() trick.

Ex.
if (strlen($foo) < 5) { echo "Foo is too short"; }
vs.
if (!isset($foo{5})) { echo "Foo is too short"; }

Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.
40. When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

Was sind eure Erfahrungen? Gibt es Ergänzungen oder Korrekturen?

Das sind die neuen Features von PHP 5.4

Samstag, Juli 2nd, 2011

Auf der Habenseite verbuchen wir:

Traits
PHP unterstützt für Objektorientierte Programmierung direkte Vererbung. Eine Klasse erbt von genau einer Oberklasse, eine Vererbung aus mehreren Quellen kann nicht erfolgen. Das führt im Zweifel wieder zu Codeduplizierung, was man mit der Objektorientierung prinzipiell zu verringern versucht. Über Traits lassen sich Codeteile in einer Klasse aus mehreren Quellen beziehen (das Beispiel liefert die Ausgabe 112):

trait A {
	public static function abc(){
		echo 1;
	}
}
 
trait B {
	public static function def(){
		echo 2;
	}
}
 
class X {
	use A;
}
 
class Y {
	use A;
	use B;
}
 
X::abc();
Y::abc();
Y::def();

Array Dereferencing
Was für Objekte schon länger funktioniert, kommt nun auch für Arrays. Gibt eine Methode ein Array zurück, lässt sich der Methodenaufruf mit einer Feldselektion vereinen - eine einfache Form des Syntax Chaining (das Beispiel gibt den buchstaben c aus):

function func() {
    return array('a', 'b', 'c');
}
echo func()[2];

Traversable MySQLi Resultsets
Die Klasse MySQLi Result implementiert nun das Interface Traversable. Praktischer Inhalt dieses technischen Einzeilers ist, dass man das Ergebnis einer MySQLi Abfrage direkt mit foreach durchlaufen kann:

$m = new mysqli('localhost', 'user', 'pass', 'datenbank');
if($result = $m->query("SELECT * FROM tabelle;")){
	foreach($result as $row){
		print_r($row);
	}
	$result->close();
}
$m->close();

Auf der Sollseite steht allerdings auch noch einiges, was für für den künftigen Entwicklungsstand erwarten - immerhin gibt es bislang nur die Alphaversionen:

Instance Method calling:
https://wiki.php.net/rfc/instance-method-call

Session Handler Class:
https://wiki.php.net/rfc/session-oo

Built-in Web Server - PHP ohne Apache:
https://wiki.php.net/rfc/builtinwebserver

Natürlich ist das nicht alles, was die Entwickler in den PHP 5.3 Nachfolger einbauen wollen. Die Liste ist lang und wer Interesse an den umgesetzten Details hat, findet das aktuelle Changelog unter NEWS auf php.net. Die Todo Liste findet sich im Wiki.

PHP 5.4 alpha 1 erschienen

Mittwoch, Juni 29th, 2011

Was an neuen Features hinzukommt, geht über die Themen hinaus, die noch vor kurzem zur Abstimmung auf der Internals-Liste standen. Enthalten sind unter anderem Traits, Array Dereferencing und DTrace Unterstützung. Darüber hinaus werden aber auch alte Zöpfe abgeschnitten, beispielsweise Register Globals oder Magic Quotes. Ebenso wandert die ext/sqlite Extension Richtung PECL. Eine vollständige Liste der Änderungen ist in Form eines Changelogs in den Seiten-News abgelegt. In der Releaseankündigung wird explizit darauf hingewiesen, dass bis zur Produktivversion noch weitere Features hinzukommen können.
Neben der obligatorischen Linuxversion steht ebenso ein Windows-Binary zum Verproben der Neuerungen bereit.

PHP 5.4 ist auf dem Weg!

Donnerstag, Juni 23rd, 2011

Auf der Internals Newsliste hat einer der beiden aktuellen Releasemanager, Stas Malyshev, das Voting für die einzuschließenden Features losgetreten. Damit rückt die kommende Version einen großen Schritt näher, nachdem vor nicht allzu langer Zeit noch über Inhalt und Versionsnummer des PHP 5.3 Nachfolgers gestritten worden ist (siehe alte Einträge auf php.internals).  Zum Ende dieser hitzigen Diskusion hat nicht zuletzt wohl auch der RFC zu einem PHP Release Prozess beigetragen.

Für die Version 5.4 stehen initial zehn Features zum Voting an. Die Liste lässt anfangs vermuten, dass es sich um ein Maintenace Release handeln wird (Deklarierung eines zentralen PHP Namespaces, Entfernen von veralteten Features wie Magic Quotes, JSON-ähnliche Syntax für Arrays). Zu guter Letzt umfasst sie aber doch noch interessante Neuigkeiten: der Session Handler bekommt eine eigene Klasse, die durch Usercode erweitert werden kann, und ein eingebauter HTTP-Server soll PHP selbst zum Webserver machen!

Auf der dazugehörigen Wikiseite findet sich darüber hinaus eine Roadmap, laut der eine erste Alphaversion noch Ende Juni 2011 veröffentlicht werden soll. Nach einer weiteren Alphaversion folgt die Beta im August und eine Reihe von Release Candidates (RC) steht ab September an. Ein Veröffentlichungstermin für die produktive Version exisitert verständlicherweise nicht, sondern ist von der Stabilität der Release Candidates abhängig.

CodeIgniter 2.0 veröffentlicht

Sonntag, Januar 30th, 2011

Das neue Major Release stellt damit einen Startpunkt für die mehrgleisige Entwicklung im (stabilen) Core und dem (hoffentlich schnelllebigen) Reactor dar. Man trennt sich von Altlasten wie beispielsweise der Unterstützung von PHP 4 und dem Scaffolding, das bereits seit einigen Versionen als deprecated gekennzeichnet war. Allerdings schneidet man zugunsten einer gradlinigen Struktur weitere Zöpfe ab (Plugins) bzw. gestaltet zentrale Stellen um (Namen der Controllerklasse, von der eigene Controller erben), so dass beim Upgrade einige Arbeit auf den Entwickler zukommt. Ein vollständiges Changelog wie auch der Download Link finden sich auf www.codeigniter.com.

Structs in PHP

Montag, Januar 24th, 2011