C’è un sacco di cattiva informazione sul web che porta i nuovi utenti di PHP fuori strada, che promuovono cattive pratiche e codice scritto male. Bisogna porre un freno a tutto ciò. PHP: Nel modo corretto fornisce una guida facile da leggere sulle migliori pratiche di PHP, sui coding standard accettati, e link a tutorial in giro per il web.
E’ importante capire non c’è modo standard di utilizzare PHP. Questa è la sua bellezza. Questo sito vuole introdurre i nuovi sviluppatori PHP alle migliori pratiche, dando tutte le opzioni a disposizione, e una buona informazione.
Questo è un documento vivo e continuerà ad essere aggiornato con le informazioni più utili ed esempi man mano che diventano disponibili.
Contribuite a rendere questo sito la miglior risorsa per i nuovi programmatori PHP! Contribuite su GitHub
PHP: Nel modo corretto ha banner ed immagini che puoi usare nel tuo sito. Mostraci il tuo aiuto, e fai conoscere ai nuovi sviluppatori PHP dove trovare buone informazioni!
Chi ha appena iniziato con PHP dovrebbe assicurarsi di iniziare con la versione stabile attuale di PHP 5.4. PHP ha fatto passi da gigante, aggiungendo potenti nuove caratteristiche negli ultimi anni. Non ci si lasci ingannare dalla differenza di versione minore tra 5.2 e 5.4, ci sono dei miglioramenti importanti.
Si può iniziare a imparare PHP senza doversi preoccupare di installare e configurare un server web completo (se si usa PHP 5.4). Per far partire il server, eseguire il comando seguente in un terminale, partendo dalla cartella radice di un progetto:
> php -S localhost:8000
Si può iniziare a imparare PHP senza doversi preoccupare di installare e configurare un server web completo (se si usa PHP 5.4). Per far partire il server, eseguire il comando seguente in un terminale, partendo dalla cartella radice di un progetto:
> php -S localhost:8000
OSX comes prepackaged with PHP but it is normally a little behind the latest stable. Lion comes with PHP 5.3.6 and Mountain Lion has 5.3.10.
To update PHP on OSX you can get it installed through a number of Mac package managers, with php-osx by Liip being recommended.
The other option is to compile it yourself, in that case be sure to have installed either Xcode or Apple’s substitute “Command Line Tools for Xcode” downloadable from Apple’s Mac Developer Center.
For a complete “all-in-one” package including PHP, Apache web server and MySQL database, all this with a nice control GUI, try MAMP.
PHP is available in several ways for Windows. You can download the binaries and until recently you could use a ‘.msi’ installer. The installer is no longer supported and stops at PHP 5.3.0.
For learning and local development you can use the built in webserver with PHP 5.4 so you don’t need to worry about configuring it. If you would like an “all-in-one” which includes a full-blown webserver and MySQL too then tools such as the Web Platform Installer, XAMPP and WAMP will help get a Windows development environment up and running fast. That said, these tools will be a little different from production so be careful of environment differences if you are working on Windows and deploying to Linux.
If you need to run your production system on Windows then IIS7 will give you the most stable and best performance. You can use phpmanager (a GUI plugin for IIS7) to make configuring and managing PHP simple. IIS7 comes with FastCGI built in and ready to go, you just need to configure PHP as a handler. For support and additional resources there is a dedicated area on iis.net for PHP.
Generally running your application on different environment in development and production can lead to strange bugs popping up when you go live. If you are developing on Windows and deploying to Linux (or anything non-Windows) then you should consider using a Virtual Machine. This sounds tricky, but using Vagrant you can set up simple wrappers, then using Puppet or Chef you can provision these boxes and share them with your colleagues to ensure you’re all working on the same stack. More on this soon.
La comunità PHP è ampia ed eterogenea, composta da innumerevoli librerie, framework e componenti. E’ normale per gli sviluppatori PHP di scegliere alcuni di questi ed utilizzarli in un unico progetto. E’ però importante, per il codice PHP aderire (il più vicino possibile) ad uno stile di codice comune per rendere più facile agli sviluppatori di combinare varie librerie per i loro progetti.
Il Framework Interop Group (conosciuto anche come ‘PHP Standards Group’) ha proposto ed approvato una serie di guide alla formattazione del testo e scrittura del codice, conosciute come PSR-0, PSR-1 e PSR-2. Non lasciatevi però confondere da queste strane sigle, queste raccomandazione sono semplicemente un insieme condiviso di regole che alcuni progetti come Drupal, Zend, CakePHP, phpBB, AWS SDK, FuelPHP, Lithium, etc hanno iniziato ad utilizzare. Potete usarle nel vostro progetto, o continuare ad usare il vostro personale stile.
Idealmente dovresti scrivere il codice PHP affinchè aderisca a uno più di questi standard in modo tale che altri sviluppatori possano facilmente leggere e lavorare con il tuo codice. Gli standard sono dipendenti da quelli precedenti, ad esempio usando PSR-1 il codice dovrà essere conforme a PSR-0, ma potrebbe non esserlo con PSR-2.
PHP is a flexible, dynamic language that supports a variety of programming techniques. It has evolved dramatically over the years, notably adding a solid object-oriented model in PHP 5.0 (2004), anonymous functions and namespaces in PHP 5.3 (2009), and traits in PHP 5.4 (2012).
PHP has had anonymous functions since PHP 5.3:
<?php
$greet = function($name)
{
print("Hello {$name}");
};
$greet('World');
Ruby developers often say that PHP is lacking method_missing, but it is available as __call(). There are many Magic Methods available like __get(), __set(), __clone(), __toString(), etc.
Come ho già detto, la comunità PHP ha un sacco di sviluppatori che creano un sacco di codice. Ciò significa che il codice PHP di una libreria potrebbe utilizzare lo stesso nome per una classe di un’altra libreria. Quando entrambe le librerie sono usate nello stesso namespace collidono e causano problemi.
I Namespaces risolvono questo problema. Come descritto nel manuale di riferimento di PHP, i namespaces possono essere paragonati alle directory di un filesystem come i namespace ai file; due file con lo stesso nome possono coesistere in directory separate. Allo stesso modo, due classi PHP con lo stesso nome possono coesistere nei namespace PHP separati. E’ così semplice.
E’ importante per voi usare i namespace all’interno del vostro codice in modo che possa essere utilizzato da altri sviluppatori, senza timore di collisioni tra librerie.
Un modo raccomandato di usare i namespace è indicato in PSR-0, che indica una convenzione standard per creare file, classi e namespace.
La Standard PHP Library (SPL) è inclusa in PHP e offre una collezione di classi ed interfacce. E’ fatta innanzitutto di classi per gestire strutture di dati (stack, queue, heap, e così via), iteratori che possono attraversare queste strutture o anche le tue classi che sfruttano le interfaccie offerte da SPL.
PHP was created primarily to write web applications, but it’s also useful for scripting command line interface (CLI) programs, too. Command line PHP programs can help you automate common tasks like testing, deployment, and application administrativia.
CLI PHP programs are powerful because you can use your app’s code directly without having to create and secure a web GUI for it. Just be sure not to put your CLI PHP scripts in your public web root!
Try running PHP from your command line:
> php -i
The -i option will print your PHP configuration just like the phpinfo function.
The -a option provides an interactive shell, similar to ruby’s IRB or python’s interactive shell. There are a number of other useful command line options, too.
Let’s write a simple “Hello, $name” CLI program. To try it out, create a file named hello.php, as below.
<?php
if($argc != 2) {
die("Usage: php hello.php [name].\n");
}
$name = $argv[1];
echo "Hello, $name\n";
PHP sets up two special variables based on the arguments your script is run with. $argc is an integer variable containing the argument count and $argv is an array variable containing each argument’s value. The first argument is always the name of your PHP script file, in this case hello.php.
To run our script, above, from the command line:
> php hello.php
Usage: php hello.php [name]
> php hello.php world
Hello, world
There are a ton of PHP libraries, frameworks, and components to choose from. Your project will likely use several of them — these are project dependencies. Until recently, PHP did not have a good way to manage these project dependencies. Even if you managed them manually, you still had to worry about autoloaders. No more.
Currently there are two major package management systems for PHP - Composer and PEAR. Which one is right for you? The answer is both.
In general, Composer packages will be available only in the projects that you explicitly specify whereas a PEAR package would be available to all of your PHP projects. While PEAR might sound like the easier approach at first glance, there are advantages to using a project-by-project approach to your dependencies.
Composer is a brilliant dependency manager for PHP. List your project’s dependencies in a composer.json file and, with a few simple commands, Composer will automatically download your project’s dependencies and setup autoloading for you.
There are already a lot of PHP libraries that are compatible with Composer, ready to be used in your project. These “packages” are listed on Packagist, the official repository for Composer-compatible PHP libraries.
You can install Composer locally (in your current working directory; though this is no longer recommended) or globally (e.g. /usr/local/bin). Let’s assume you want to install Composer locally. From your project’s root directory:
curl -s http://getcomposer.org/installer | php
This will download composer.phar (a PHP binary archive). You can run this with php to manage your project dependencies. Please Note: If you pipe downloaded code directly into an interpreter, please read the code online first to confirm it is safe.
Manually installing composer is an advanced technique; however, there are various reasons why a developer might prefer this method vs. using the interactive installation routine. The interactive installation checks your PHP installation to ensure that:
.phar files can be executed correctlyphp.ini settings are setSince a manual installation performs none of these checks, you have to decide whether the trade-off is worth it for you. As such, below is how to obtain Composer manually:
curl -s http://getcomposer.org/composer.phar -o $HOME/local/bin/composer
chmod +x $HOME/local/bin/composer
The path $HOME/local/bin (or a directory of your choice) should be in your $PATH environment variable. This will result in a composer command being available.
When you come across documentation that states to run Composer as php composer.phar install, you can substitute that with:
composer install
First, create a composer.json file in the same directory as composer.phar. Here’s an example that lists Twig as a project dependency.
{
"require": {
"twig/twig": "1.8.*"
}
}
Next, run this command from your project root directory.
php composer.phar install
This will download and install the project dependencies into a vendors/ directory. Next, add this line to your application’s primary PHP file; this will tell PHP to use Composer’s autoloader for your project dependencies.
<?php
require 'vendor/autoload.php';
Now you can use your project dependencies, and they’ll be autoloaded on demand.
Un altro, vecchio, sistema di gestione pacchetti che molti sviluppatori PHP apprezzano è PEAR. Funziona più o meno nello stesso modo, e vale la pena studiarlo per i vostri progetti.
Exceptions are a standard part of most popular programming languages, but they are often overlooked by PHP programmers. Languages like Ruby are extremely Exception heavy, so whenever something goes wrong such as a HTTP request failing, or a DB query goes wrong, or even if an image asset could not be found, Ruby (or the gems being used) will throw an exception to the screen meaning you instantly know there is a mistake.
PHP itself is fairly lax with this, and a call to file_get_contents() will usually just get you a FALSE and a warning. Many older PHP frameworks like CodeIgniter will just return a false, log a message to their proprietary logs and maybe let you use a method like $this->upload->get_error() to see what went wrong. The problem here is that you have to go looking for a mistake and check the docs to see what the error method is for this class, instead of having it made extremely obvious.
Another problem is when classes automatically throw an error to the screen and exit the process. When you do this you stop another developer from being able to dynamically handle that error. Exceptions should be throw to make a developer aware of an error, then they can choose how to handle this. E.g:
<?php
$email = new Fuel\Email;
$email->subject('My Subject');
$email->body('How the heck are you?');
$email->to('guy@example.com', 'Some Guy');
try
{
$email->send();
}
catch(Fuel\Email\ValidationFailedException $e)
{
// The validation failed
}
catch(Fuel\Email\SendingFailedException $e)
{
// The driver could not send the email
}
An Exception by default has no meaning and the most common to give it meaning is by setting its name:
<?php
class ValidationException extends Exception {}
This means you can add multiple catch blocks and handle different Exceptions differently. This can lead to the creation of a lot of custom Exceptions, some of which could have been avoided using the SPL Exceptions provided in the SPL extension.
If for example you use the __call() Magic Method and an invalid method is requested then instead of throwing a standard Exception which is vague, or creating a custom Exception just for that, you could just throw new BadFunctionCallException;.
Many times your PHP code will use a database to persist information. You have a few options to connect and interact with your database. The recommended option until PHP 5.1.0 was to use native drivers such as mysql, mysqli, pgsql, etc.
Native drivers are great if you are only using ONE database in your application, but if, for example, you are using MySQL and a little bit of MSSQL, or you need to connect to an Oracle database, then you will not be able to use the same drivers. You’ll need to learn a brand new API for each database — and that can get silly.
As an extra note on native drivers, the mysql extension for PHP is no longer in active development, and the official status since PHP 5.4.0 is “Long term deprecation”. This means it will be removed within the next few releases, so by PHP 5.6 (or whatever comes after 5.5) it may well be gone. If you are using mysql_connect() and mysql_query() in your applications then you will be faced with a rewrite at osme point down the line, so the best option is to replace mysql usage with mysqli or PDO in your applications within your own development shedules so you won’t be rushed later on. If you are starting from scratch then absolutely do not use the mysql extension: use the MySQLi extension, or use PDO.
PDO is a database connection abstraction library — built into PHP since 5.1.0 — that provides a common interface to talk with many different databases. PDO will not translate your SQL queries or emulate missing features; it is purely for connecting to multiple types of database with the same API.
More importantly, PDO allows you to safely inject foreign input (e.g. IDs) into your SQL queries without worrying about database SQL injection attacks. This is possible using PDO statements and bound parameters.
Let’s assume a PHP script receives a numeric ID as a query parameter. This ID should be used to fetch a user record from a database. This is the wrong way to do this:
<?php
$pdo = new PDO('sqlite:users.db');
$pdo->query("SELECT name FROM users WHERE id = " . $_GET['id']); // <-- NO!
This is terrible code. You are inserting a raw query parameter into a SQL query. This will get you hacked in a heartbeat. Instead, you should sanitize the ID input using PDO bound parameters.
<?php
$pdo = new PDO('sqlite:users.db');
$stmt = $pdo->prepare('SELECT name FROM users WHERE id = :id');
$stmt->bindParam(':id', filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT), PDO::PARAM_INT);
$stmt->execute();
This is correct code. It uses a bound parameter on a PDO statement. This escapes the foreign input ID before it is introduced to the database preventing potential SQL injection attacks.
Many frameworks provide their own abstraction layer which may or may not sit on top of PDO. These will often emulate features for one database system that another is missing form another by wrapping your queries in PHP methods, giving you actual database abstraction. This will of course add a little overhead, but if you are building a portable application that needs to work with MySQL, PostgreSQL and SQLite then a little overhead will be worth it the sake of code cleanliness.
Some abstraction layers have been built using the PSR-0 namespace standard so can be installed in any application you like:
In rete, ci sono cattive persone che vorrebbero bucare la vostra applicazione. E’ quindi importante prendere sempre le corrette precauzioni per rendere le applicazioni sicure. Fortunatamente, gli amici del The Open Web Application Security Project (OWASP) hanno compilato una lista comprensiva delle principali problematiche di sicurezza e dei migliori medoti per proteggerci da esse. Questa lista è sicuramente una lettura indispensabile per ogni sviluppatore che ci tenga alla sicurezza delle proprie applicazioni.
Alla fine, la maggior parte delle applicazioni PHP, richiedono l’accesso degli utenti. Nomi utente e password (criptate) sono archiviate nella base di dati e usate successivamente per autenticare gli utenti durante l’accesso.
E’ importante criptare adeguatamente le password che sono archiviate nelal pase di dati. Se una password non è criptata e la base di dati viene attaccata o è accessibile ad utenti di terze parti non autorizzati, tutte le credenziali degli utenti saranno compromesse.
Criptare una password con Bcrypt. E’ molto semplce e (a tutti gli effetti) Bcrypt rende impossibile per qualcuno risalire alla versione iniziale della password, anche se la base di dati viene compromessa.
Ci sono diverse librerie Bcrypt per PHP che possono essere usate.
Nel vostro codice PHP non dovete mai e poi mai ( ma proprio mai ) dar fiducia all’input proveniente dall’esterno. E’ un attaggiamento che porta in luoghi oscuri e pericolosi. Invece, è opportuno filtrare sempre l’input esterno prima di usarlo.
Foreign input can be anything: $_GET and $_POST form input data, some values in the $_SERVER superglobal, and the HTTP request body via fopen('php://input', 'r'). Remember, foreign input is not limited to form data submitted by the user. Uploaded and downloaded files, session values, cookie data, and data from third-party web services are foreign input, too.
While foreign data can be stored, combined, and accessed later, it is still foreign input. Every time you process, output, concatenate, or include data in your code, ask yourself if the data is filtered properly and can it be trusted.
Data may be filtered differently based on its purpose. For example, when unfiltered foreign input is passed into HTML page output, it can execute HTML and JavaScript on your site! This is known as Cross-Site Scripting (XSS) and can be a very dangerous attack. One way to avoid XSS is to sanitize all HTML tags in the input by removing tags or escaping them into HTML entities.
Another example is passing options to be executed on the command line. This can be extremely dangerous (and is usually a bad idea), but you can use the built-in escapeshellarg function to sanitize the executed command’s arguments.
One last example is accepting foreign input to determine a file to load from the filesystem. This can be exploited by changing the filename to a file path. You need to remove ”/”, “../”, null bytes, or other characters from the file path so it can’t load hidden, non-public, or sensitive files.
filter_varfilter_inputSanitization removes (or escapes) illegal or unsafe characters from foreign input.
For example, you should sanitize foreign input before including the input in HTML or inserting it into a raw SQL query. When you use bound parameters with PDO, it will sanitize the input for you.
Sometimes it is required to allow some safe HTML tags in the input when including it in the HTML page. This is very hard to do and many avoid it by using other more restricted formatting like Markdown or BBCode, although whitelisting libraries like HTML Purifier exists for this reason.
Validation ensures that foreign input is what you expect. For example, you may want to validate an email address, a phone number, or age when processing a registration submission.
Writing automated tests for your PHP code is considered a best practice and can lead to well-built applications. Automated tests are a great tool for making sure your application does not break when you are making changes or adding new functionality and should not be ignored.
There are several different types of testing tools (or frameworks) available for PHP, which use different approaches - all of which are trying to avoid manual testing and the need for large Quality Assurance teams, just to make sure recent changes didn’t break existing functionality.
From Wikipedia:
Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes a failing automated test case that defines a desired improvement or new function, then produces code to pass that test and finally refactors the new code to acceptable standards. Kent Beck, who is credited with having developed or ‘rediscovered’ the technique, stated in 2003 that TDD encourages simple designs and inspires confidence
There are several different types of testing that you can do for your application
Unit Testing is a programming approach to ensure functions, classes and methods are working as expected, from the point you build them all the way through the development cycle. By checking values going in and out of various functions and methods, you can make sure the internal logic is working correctly. By using Dependency Injection and building “mock” classes and stubs you can verify that dependencies are correctly used for even better test coverage.
When you create a class or function you should create a unit test for each behavior it must have. At a very basic level you should make sure it errors if you send it bad arguments and make sure it works if you send it valid arguments. This will help ensure that when you make changes to this class or function later on in the development cycle that the old functionality continues to work as expected. The only alternative to this would be var_dump() in a test.php, which is no way to build an application - large or small.
The other use for unit tests is contributing to open source. If you can write a test that shows broken functionality (i.e. fails), then fix it, and show the test passing, patches are much more likely to be accepted. If you run a project which accepts pull requests then you should suggest this as a requirement.
PHPUnit is the de-facto testing framework for writing unit tests for PHP applications, but there are several alternatives
From Wikipedia:
Integration testing (sometimes called Integration and Testing, abbreviated “I&T”) is the phase in software testing in which individual software modules are combined and tested as a group. It occurs after unit testing and before validation testing. Integration testing takes as its input modules that have been unit tested, groups them in larger aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the integrated system ready for system testing.
Many of the same tools that can be used for unit testing can be used for integration testing as many of the same principles are used.
Sometimes also known as acceptance testing, functional testing consists of using tools to create automated tests that actually use your application instead of just verifying that individual units of code are behaving correctly and that individual units can speak to each other correctly. These tools typically work using real data and simulating actual users of the application.
There are two different types of Behavior-Driven Development (BDD): SpecBDD and StoryBDD. SpecBDD focuses on technical behavior or code, while StoryBDD focuses on business or feature behaviors or interactions. PHP has frameworks for both types of BDD.
With StoryBDD, you write human-readable stories that describe the behavior of your application. These stories can then be run as actual tests against your application. The framework used in PHP applications for StoryBDD is Behat, which is inspired by Ruby’s Cucumber project and implements the Gherkin DSL for describing feature behavior.
With SpecBDD, you write specifications that describe how your actual code should behave. Instead of testing a function or method, you are describing how that function or method should behave. PHP offers the PHPSpec framework for this purpose. This framework is inspired by the RSpec project for Ruby.
Oltre ai framework per fare test individuale e di comportamento, ci sono ulteriori strumenti e librerie utili a fare test del codice seguendo approcci differenti.
Le applicazioni PHP possono essere distribuite, o installate, e funzionare sui server di produzione in diversi modi.
PaaS offrono le risorse e l’architettura di rete necessari a far funzionare applicazioni PHP su internet. Il tutto con niente, o pochissima, configurazione dei sistemi per far funziona l’applicazione o il framework PHP.
Ultimamente i PaaS sono diventati molto popolari per far funzionare (e scalare) applicazioni PHP di qualsiasi dimensione. Puoi trovarei una lista di PHP PaaS “Platform as a Service” provider nella nostra sezione sulle risorse e link.
If you are comfortable with systems administration, or are interested in learning it, virtual or dedicated servers give you complete control of your application’s production environment.
PHP, via PHP’s built-in FastCGI Process Manager (FPM), pairs really nicely with nginx, which is a lightweight, high-performance web server. It uses less memory than Apache and can better handle more concurrent requests. This is especially important on virtual servers that don’t have much memory to spare.
PHP and Apache have a long history together. Apache is wildly configurable and has many available modules to extend functionality. It is a popular choice for shared servers and an easy setup for PHP frameworks and open source apps like WordPress. Unfortunately, Apache uses more resources than nginx by default and cannot handle as many visitors at the same time.
Apache has several possible configurations for running PHP. The most common and easiest to setup is the prefork MPM with mod_php5. While it isn’t the most memory efficient, it is the simplest to get working and to use. This is probably the best choice if you don’t want to dig too deeply into the server administration aspects. Note that if you use mod_php5 you MUST use the prefork MPM.
Alternatively, if you want to squeeze more performance and stability out of Apache then you can take advantage of the same FPM system as nginx and run the worker MPM or event MPM with mod_fastcgi or mod_fcgid. This configuration will be significantly more memory efficient and much faster but it is more work to set up.
PHP deve ringraziare i server condivisi per la sua popolarità. E’ difficile trovare un host, che non abbia installato PHP, bisogna fare però attenzione che, quella installata, sia l’ultima versione. I server condivisi permettono a te ed a tutti gli altri sviluppatori di far funzionare diversi siti su una stessa macchina. L’economicità ne è un sicuro vantaggio che ne emerge. Purtroppo lo svantaggio è che non si sa mai che tipo di casini i vostri coinquilini potrebbero creare; caricare il server o l’apertura di falle di sicurezza sono le principali preoccupazioni da tenere a mente. Se avete un buon budget per il vostro progetto il suggerimento è di evitare i server condivisi.
Anche se PHP è di per sè molto veloce, colli di bottiglia possono rallentarlo quando si caricano file, si accedono a risorse esternet, etc. Fortunatamente, ci sono diversi strumenti per velocizzare certe parti della vostra applicazione, o per ridurre il numero di volte che queste attività che rallentano siano eseguite.
When a PHP file is executed, under the hood it is first compiled to bytecode (also known as opcode) and, only then, the bytecode is executed. If a PHP file is not modified, the bytecode will always be the same. This means that the compilation step is a waste of CPU resources.
This is where Bytecode cache comes in. It prevents redundant compilation by storing bytecode in memory and reusing it on successive calls. Setting up bytecode cache is a matter of minutes, and your application will speed up significantly. There’s really no reason not to use it.
Popular bytecodes caches are:
There are times when it can be beneficial to cache individual objects in your code, such as with data that is expensive to get or database calls where the result is unlikely to change. You can use object caching software to hold these pieces of data in memory for extremely fast access later on. If you save these items to a data store after you retrieve them, then pull them directly from the cache for following requests you can gain a significant improvement in performance as well as reduce the load on your database servers.
Many of the popular bytecode caching solutions let you cache custom data as well, so there’s even more reason to take advantage of them. APC, XCache, and WinCache all provide APIs to save data from your PHP code to their memory cache.
The most commonly used memory object caching systems are APC and memcached. APC is an excellent choice for object caching, it includes a simple API for adding your own data to its memory cache and is very easy to setup and use. The one real limitation of APC is that it is tied to the server it’s installed on. Memcached on the other hand is installed as a separate service and can be accessed across the network, meaning that you can store objects in a hyper-fast data store in a central location and many different systems can pull from it.
In a networked configuration APC will usually outperform memcached in terms of access speed, but memcached will be able to scale up faster and further. If you do not expect to have multiple servers running your application, or do not need the extra features that memcached offers then APC is probably your best choice for object caching.
Example logic using APC:
<?php
$data = apc_fetch('expensive_data');
if (!$data)
{
$data = get_expensive_data();
apc_store('expensive_data', $data);
}
Learn more about popular object caching systems:
# Framework
Piuttosto che reinventare la ruota, molti sviluppatori PHP usano framework per costruire le proprie applicazioni web. I framework astraggono molto del lavoro a basso libello e offrono interfacce comode e semplici per completare i task più comuni.
Non avete bisogno di usare un framework in ogni progettto. Qualche volta, l’utilizzo di semplice PHP è il miglior modo di proseguire. Ma se necessitate di usare un framework è importante sapere che possono essere suddivisi in tre tipologie:
I Micro framework si basano sul concetto di associare ad una richiesta HTTP un particolare callback, metodo, controller, etc nel più veloce modo possibile, e (qualche volta) con l’aiuto di qualche libreria extra, ad esempio per usare un database, per semplificare il lavoro di uno sviluppatore. Tendenzialmente i mini framework sono usati per costruire servizi remoti basati su HTTP.
I framework che aggiungono un considerevole numero di funzionalità oltre a quelle che sono disponibili nei micro framework sono noti come Full-Stack Framework. Vengono normalmente distribuiti con ORM, sistemi di autenticazione, etc.
I framework di componenti sono collezioni di librerie specializzate a svolgere un unico scopo. Diversi framework di componenti posso essere usati insieme per costruire micro o full-stack framework.
La comunità di PHP è sia grande che eterogenea, ed i suoi membri sono sempre pronti ad aiutare nuovi sviluppatori che si avvicinano al linguaggio. Per imparare le migliori pratiche potete considerare di partecipare al PHP User Group (PUG) locale o ad una delle maggiori conferenze su PHP. Esiste anche un canale IRC chiamato #phpc su irc.freenode.com dove chiaccherare o seguire l’account twitter @phpc. Esci un po’, incontra nuovi sviluppatori, impara nuovi argomenti e fatti nuovi amici.
Segui il calendario ufficiale degli eventi PHP
Se vivi in una grande città, è probabile che ci sia un PHP User Group nelle vicinanze. Nonostante non ci sia ancora una lista ufficiale dei PUG, puoi sempre cercare il PUG più vicino a te usando Google o Meetup.com. Se vivi in una città piccolina potrebbero non esserci PUG, in tal caso… perchè non aprirne uno tu?
Leggi informazioni sui PHP User Groups sul Wiki di PHP
The PHP community also hosts larger regional and national conferences in many countries around the world. Well-known members of the PHP community usually speak at these larger events, so it’s a great opportunity to learn directly from industry leaders.