programming best practices (php)
TRANSCRIPT
What will you be able to do?Goal: Write safer, faster and more robust PHP code
Agenda1. Coding Style2. Coding Practices3. Security4. Errors and Exceptions
Coding Style - Namespaces
• Huge PHP community = lots of code• If 2 libraries share same class name = oh oh, troubles…• Namespaces are similar to “OS directories”,
– 2 files with same name can co-exist in separate directories
– 2 classes with same name can co-exist in separate PHP namespaces
Coding Style - Namespaces - Ex
Code example
Coding Style - PSR-X
• PSR = PHP Standards Recommendations
• Coding style followed by most frameworks and latest libraries.
• Ex PSR-2 https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
Coding Practices
• DRY code ( Don’t Repeat Yourself)– Create functions and reuse them whenever you have code very similar
in different parts of your applications
• Use Object Oriented Programming whenever possible– Create classes to run your business logic (1 class per file if possible)
Coding Practices
• Separate template code from business logic– Your template files should only load and display data, no processing– Your class files should not start/run themselves and should not directly
display content (your methods can)
Security
• Input Validation
• SQL Injection
Security - Input Validation
• Never trust user input• Always test if an input or variable exist
– isset($variable) = test if variable is not NULL– empty($array) = test if array is empty
• Then filter that input to make sure you receive what you expected– filter_var (for any kind of variables)– filter_input (for form inputs)
Security - Input Validation
Security - Input Validation
Security - SQL Injection
Security - SQL Injection
• Use PDO prepare statements (Laravel Eloquent uses it by default and Wordpress has its own prepare statements
Errors & Exceptions - Errors
• PHP is an “exception-light” programming language.
• Unless a “fatal error” occurs, most of PHP will try to keep processing
• 3 types of error severity:• E_ERROR,E_NOTICE, and E_WARNING
Errors & Exception - ErrorException Class
• Throw your “errors” as “exceptions” using the ErrorException class, which extends the Exception class.
• Common practice for several frameworks (Laravel, Symphony, etc.)
• Allow to handle errors better than the usual result by “catching” exceptions
Errors & Exceptions - Exceptions
• Exceptions are often overlooked by PHP programmers.
• Some old PHP frameworks returns “false” or “Warning” when something goes wrong.– You have to dig in the doc and reread the code to
find what’s wrong
Errors & Exceptions - Exceptions
You Do
Each of you will apply the techniques we learnedtoday to optimize/secure/clean your previousprojects.Make sure to version your previous code before making any changes so I can see the progression
Resources
• http://www.phptherightway.com/