SlideShare a Scribd company logo
1 of 31
Download to read offline
Standard Coding, OOP Techniques and
Code Reuse
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 2
Standard Coding
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 3
What isWhat is Standard CodingStandard Coding??
● Clean, smart and readable code
● Follows a coding standard
● Streamlined to the purpose
“Code is Art”
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 4
Why Standard Coding?
● Code Quality
● Less buggy
● Maintainability
● Scalability
● Collaboration
(Readability)
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 5
Coding Standards
● Zend Coding Standard
- The most advanced coding standard in PHP
● PEAR Coding Standards
- Base for most of the coding standards in PHP
● CakePHP Coding Standard
● CodeIgniter Coding Standard
Note: There are tons of bad & inconsistent coding standards in
PHP
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 6
Code Commenting
● Remember! Doc-block is must for File, Class and Method
● Always in phpDocumentor format, don't put your own tag
● Latest PHP IDE like NetBeans, Zend Studio, Eclipse PDT
can help you generating doc-block easily
● Benefit
● Documentation is done as you go with coding
● Doxygen can build your API documentation in chm
format instantly from your code
● IDE like netbeans shows code hints, code completion
along with popup documentation on the fly
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 7
See, netbeans can show
documentation on the fly
for you
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 8
Standard Coding - Tips
● Say no to short tags <? ?>, always long tags (<?php ?>)
● Use foreach instead of for loop for array iteration
● Ensure variable is not empty before any iteration
● Use null as default function parameter if possible
● Avoid nested conditions, return as early as possible
● Use alternative syntax for control structures when mixing
with HTML
if ():
else:
endif;
foreach ():
endforeach;
for ():
endfor;
while ():
endwhile;
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 9
Standard Coding – empty
●
empty() is a magic in php, learn how to use it, at
the end you will love it
● Use !empty() instead of isset() when working
with non-empty or non-zero value
● Use !empty($array) instead of count($array)
when checking if array has value
● Always check your variable before going further with
it
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 10
array functions = green power
● Learn them all, specially: in_array,
array_merge, array_map,
array_values, array_keys, join,
explode!
● They can save your time!
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 11
Clean and Smart
Clean and Smart
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 12
OOP Techniques
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 13
Static Method & Variables
● Ever used Configure::read() in CakePHP.
● Remember! Public static method can be accessed
from any part of your application
● No more global function, move them to a wrapper
class with static method
● All methods in Sanitize, Set and String among other
classes in CakePHP are static
● Extensively used in Zend Framework too
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 14
One-time/Magic Configuration
● Tired of multiple setters! Or you can't remember the
order of parameters
● $options array as function parameter instead of
multiple parameters or multiple setters
● setConfig() method, in constructor call
setConfig(), do not bypass.
● Ensure configure and reconfigure ability
● Chain your method if possible
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 15
Design PatternsDesign Patterns
●
Solve common design problems not coding problems
● Singleton, Factory and MVC patterns are common
● Worth learning: Registry, Adapter, Decorator, Observer and
Strategy patterns
● Same task can be done using different patterns, so choose
wisely!
● Reminder! Patterns are not perfect, they have week points
too
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 16
Singleton - Design Pattern
●
Ensure a class has only one instance
● Provide a global point of access to it
● Mostly used in application level Configuration,
Logging, Database etc
● CakePHP uses extensive number of singleton
classes like Configure, Router, App with static
method etc
● Lazy initialization
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 17
class Logger {
protected static $_instance;
private function __construct($options = null) {}
public static function &getInstance($options = null)
{
If (is_null(self::$_instance)) {
self::$_instance = new self($options);
}
return self::$_instance;
}
public function write($message, $type = null) {}
}
Logger::getInstance()->write('My log message');
// Or
$Logger = Logger::getInstance();
$Logger->write('My log message!');
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 18
class Logger {
protected static $_instance;
private function __construct($options = null) {}
public static function &getInstance($options = null) {
if (is_null(self::$_instance)) {
self::$_instance = new self($options);
}
return self::$_instance;
}
protected function _write($message, $type = null) {}
public static function write($message, $type = null) {
$_this = self::getInstance();
$_this->_write($message, $type = null);
}
}
Logger::write('My log message!');
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 19
Order the factory
to get
your favorite jeans
Factory MethodFactory Method
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 20
Factory Method - Design Pattern
● Single interface for creating instance from a family of
classes that can do the same task in multiple ways
● Reduce platform dependency
● Example:
● Database Driver
– mysqli, sqlite, oracle, postgres, odbc, mssql
● Authentication
– Database, LDAP, OpenID etc
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 21
class DatabaseDriver {
static function &factory($driver = null, $options =
null) {
switch ($driver) {
case 'postgres':
return PostgresDriver($options);
case 'sqlite':
return SQLiteDriver($options);
default:
return MySQLiDriver($options);
}
}
}
$DbDriver = DatabaseDriver::factory('mysqli');
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 22
MVC - Design Patterns
● Separate presentation, decision making and data
layer
● Web is MVC
● So, your web application should be
● Zend Framework, CakePHP, CodeIgniter all are
MVC
StorageClient Server
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 23
ORM – Object Relational Mapping
● Raw SQL? No more!
● ORM is more flexible, efficient and maintainable
● CakePHP has built-in ORM through association
● Zend has Relationships using Zend_Db_Table
● Doctrine and Propel are most popular ORM in PHP
● Doctrine can be used with both Zend Framework &
CodeIgniter
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 24
Abstract Class
● Incomplete implementation of some concept
● You can implement multiple Interfaces but extend
from only one abstract class
● You can't create instance of an Abstract Class
● Type hinting, enforce object type
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 25
Code Reuse
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 26
Code Reuse – when and how?
● Don't Re-Invent the Wheel
● But, you can always Improve the Wheel
● Decide when to Reuse
● Got a peace of code that can perform a specific task
individually
● No copy & paste of the same code, put them inside a
wrapper class and call whenever you need.
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 27
Wrap your code
● Say you have got a
piece of code for
updating Twitter
Status
● First, separate
configuration variable
like apiUrl,
username and
password
● Separate variables
that are specific to
call, like message
● Write your update
method
class Twitter {
protected $_configs = array(
'apiUrl' => '_api_url_',
'username' => '',
'password' => ''
);
function __construct($options)
{
$this->_configs =
$options; }
function setConfig($options);
function update($message);
}
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 28
Avoid DependencyAvoid Dependency
● My belief “Always keep the door open”
● Loosely coupled classes are reusable
● Make your class independent and flexible as much
as you can
● Avoid dependency on global variables,
constants, files, paths, system parameters
● Use dependency injection if necessary
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 29
Share Your Code
● Your Blog
● PHPClasses.org
● Google Code
● Github.com
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 30
Question and Answer
?
phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 31
Source
● All images are taken from flickr.com

More Related Content

What's hot

Writing High Quality Code in C#
Writing High Quality Code in C#Writing High Quality Code in C#
Writing High Quality Code in C#Svetlin Nakov
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...DevDay.org
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for javamaheshm1206
 
Standard java coding convention
Standard java coding conventionStandard java coding convention
Standard java coding conventionTam Thanh
 
Understanding, measuring and improving code quality in JavaScript
Understanding, measuring and improving code quality in JavaScriptUnderstanding, measuring and improving code quality in JavaScript
Understanding, measuring and improving code quality in JavaScriptMark Daggett
 
Euro python 2015 writing quality code
Euro python 2015   writing quality codeEuro python 2015   writing quality code
Euro python 2015 writing quality coderadek_j
 
Code review
Code reviewCode review
Code reviewdqpi
 
Standards For Java Coding
Standards For Java CodingStandards For Java Coding
Standards For Java CodingRahul Bhutkar
 
Tdd in php a brief example
Tdd in php   a brief exampleTdd in php   a brief example
Tdd in php a brief exampleJeremy Kendall
 
Code Review
Code ReviewCode Review
Code ReviewDivante
 
Code quality
Code qualityCode quality
Code qualityProvectus
 
Mps Presentation
Mps PresentationMps Presentation
Mps Presentationguestaa97d9
 

What's hot (20)

Coding conventions
Coding conventionsCoding conventions
Coding conventions
 
Coding standard
Coding standardCoding standard
Coding standard
 
Coding conventions
Coding conventionsCoding conventions
Coding conventions
 
Writing High Quality Code in C#
Writing High Quality Code in C#Writing High Quality Code in C#
Writing High Quality Code in C#
 
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
[DevDay2018] Let’s all get along. Clean Code please! - By: Christophe K. Ngo,...
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Standard java coding convention
Standard java coding conventionStandard java coding convention
Standard java coding convention
 
Understanding, measuring and improving code quality in JavaScript
Understanding, measuring and improving code quality in JavaScriptUnderstanding, measuring and improving code quality in JavaScript
Understanding, measuring and improving code quality in JavaScript
 
Euro python 2015 writing quality code
Euro python 2015   writing quality codeEuro python 2015   writing quality code
Euro python 2015 writing quality code
 
Code review
Code reviewCode review
Code review
 
Standards For Java Coding
Standards For Java CodingStandards For Java Coding
Standards For Java Coding
 
Tdd in php a brief example
Tdd in php   a brief exampleTdd in php   a brief example
Tdd in php a brief example
 
Code Review
Code ReviewCode Review
Code Review
 
Code Review
Code ReviewCode Review
Code Review
 
Code Review
Code ReviewCode Review
Code Review
 
Java & J2EE Coding Conventions
Java & J2EE Coding ConventionsJava & J2EE Coding Conventions
Java & J2EE Coding Conventions
 
Code quality
Code qualityCode quality
Code quality
 
Codings Standards
Codings StandardsCodings Standards
Codings Standards
 
Quality culture
Quality cultureQuality culture
Quality culture
 
Mps Presentation
Mps PresentationMps Presentation
Mps Presentation
 

Similar to Standard Coding, OOP Techniques and Code Reuse

Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Mark Niebergall
 
Code quality tools for dev
Code quality tools for devCode quality tools for dev
Code quality tools for devDeepu S Nath
 
Php7 extensions workshop
Php7 extensions workshopPhp7 extensions workshop
Php7 extensions workshopjulien pauli
 
Workshop: Refactoring Legacy PHP: The Complete Guide
Workshop: Refactoring Legacy PHP: The Complete Guide Workshop: Refactoring Legacy PHP: The Complete Guide
Workshop: Refactoring Legacy PHP: The Complete Guide Junade Ali
 
Dmytro Dziubenko "Developer's toolchain"
Dmytro Dziubenko "Developer's toolchain"Dmytro Dziubenko "Developer's toolchain"
Dmytro Dziubenko "Developer's toolchain"Fwdays
 
Drupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesDrupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesShabir Ahmad
 
Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoringYuriy Gerasimov
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfAAFREEN SHAIKH
 
OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical MementoOdoo
 
2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratiehcderaad
 
IDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentIDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentAbid Malik
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practicesmanugoel2003
 
PhpSpec: practical introduction
PhpSpec: practical introductionPhpSpec: practical introduction
PhpSpec: practical introductionDave Hulbert
 

Similar to Standard Coding, OOP Techniques and Code Reuse (20)

More about PHP
More about PHPMore about PHP
More about PHP
 
Php
PhpPhp
Php
 
Php
PhpPhp
Php
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
 
Code quality tools for dev
Code quality tools for devCode quality tools for dev
Code quality tools for dev
 
Php7 extensions workshop
Php7 extensions workshopPhp7 extensions workshop
Php7 extensions workshop
 
Becoming A Php Ninja
Becoming A Php NinjaBecoming A Php Ninja
Becoming A Php Ninja
 
Workshop: Refactoring Legacy PHP: The Complete Guide
Workshop: Refactoring Legacy PHP: The Complete Guide Workshop: Refactoring Legacy PHP: The Complete Guide
Workshop: Refactoring Legacy PHP: The Complete Guide
 
Dmytro Dziubenko "Developer's toolchain"
Dmytro Dziubenko "Developer's toolchain"Dmytro Dziubenko "Developer's toolchain"
Dmytro Dziubenko "Developer's toolchain"
 
Drupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesDrupal 8 - Core and API Changes
Drupal 8 - Core and API Changes
 
Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoring
 
Hsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdfHsc IT 5. Server-Side Scripting (PHP).pdf
Hsc IT 5. Server-Side Scripting (PHP).pdf
 
OpenERP Technical Memento
OpenERP Technical MementoOpenERP Technical Memento
OpenERP Technical Memento
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie
 
IDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentIDE and Toolset For Magento Development
IDE and Toolset For Magento Development
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
PhpSpec: practical introduction
PhpSpec: practical introductionPhpSpec: practical introduction
PhpSpec: practical introduction
 
Software Development with PHP & Laravel
Software Development  with PHP & LaravelSoftware Development  with PHP & Laravel
Software Development with PHP & Laravel
 
Clean Code V2
Clean Code V2Clean Code V2
Clean Code V2
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Standard Coding, OOP Techniques and Code Reuse

  • 1. Standard Coding, OOP Techniques and Code Reuse
  • 2. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 2 Standard Coding
  • 3. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 3 What isWhat is Standard CodingStandard Coding?? ● Clean, smart and readable code ● Follows a coding standard ● Streamlined to the purpose “Code is Art”
  • 4. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 4 Why Standard Coding? ● Code Quality ● Less buggy ● Maintainability ● Scalability ● Collaboration (Readability)
  • 5. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 5 Coding Standards ● Zend Coding Standard - The most advanced coding standard in PHP ● PEAR Coding Standards - Base for most of the coding standards in PHP ● CakePHP Coding Standard ● CodeIgniter Coding Standard Note: There are tons of bad & inconsistent coding standards in PHP
  • 6. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 6 Code Commenting ● Remember! Doc-block is must for File, Class and Method ● Always in phpDocumentor format, don't put your own tag ● Latest PHP IDE like NetBeans, Zend Studio, Eclipse PDT can help you generating doc-block easily ● Benefit ● Documentation is done as you go with coding ● Doxygen can build your API documentation in chm format instantly from your code ● IDE like netbeans shows code hints, code completion along with popup documentation on the fly
  • 7. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 7 See, netbeans can show documentation on the fly for you
  • 8. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 8 Standard Coding - Tips ● Say no to short tags <? ?>, always long tags (<?php ?>) ● Use foreach instead of for loop for array iteration ● Ensure variable is not empty before any iteration ● Use null as default function parameter if possible ● Avoid nested conditions, return as early as possible ● Use alternative syntax for control structures when mixing with HTML if (): else: endif; foreach (): endforeach; for (): endfor; while (): endwhile;
  • 9. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 9 Standard Coding – empty ● empty() is a magic in php, learn how to use it, at the end you will love it ● Use !empty() instead of isset() when working with non-empty or non-zero value ● Use !empty($array) instead of count($array) when checking if array has value ● Always check your variable before going further with it
  • 10. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 10 array functions = green power ● Learn them all, specially: in_array, array_merge, array_map, array_values, array_keys, join, explode! ● They can save your time!
  • 11. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 11 Clean and Smart Clean and Smart
  • 12. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 12 OOP Techniques
  • 13. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 13 Static Method & Variables ● Ever used Configure::read() in CakePHP. ● Remember! Public static method can be accessed from any part of your application ● No more global function, move them to a wrapper class with static method ● All methods in Sanitize, Set and String among other classes in CakePHP are static ● Extensively used in Zend Framework too
  • 14. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 14 One-time/Magic Configuration ● Tired of multiple setters! Or you can't remember the order of parameters ● $options array as function parameter instead of multiple parameters or multiple setters ● setConfig() method, in constructor call setConfig(), do not bypass. ● Ensure configure and reconfigure ability ● Chain your method if possible
  • 15. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 15 Design PatternsDesign Patterns ● Solve common design problems not coding problems ● Singleton, Factory and MVC patterns are common ● Worth learning: Registry, Adapter, Decorator, Observer and Strategy patterns ● Same task can be done using different patterns, so choose wisely! ● Reminder! Patterns are not perfect, they have week points too
  • 16. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 16 Singleton - Design Pattern ● Ensure a class has only one instance ● Provide a global point of access to it ● Mostly used in application level Configuration, Logging, Database etc ● CakePHP uses extensive number of singleton classes like Configure, Router, App with static method etc ● Lazy initialization
  • 17. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 17 class Logger { protected static $_instance; private function __construct($options = null) {} public static function &getInstance($options = null) { If (is_null(self::$_instance)) { self::$_instance = new self($options); } return self::$_instance; } public function write($message, $type = null) {} } Logger::getInstance()->write('My log message'); // Or $Logger = Logger::getInstance(); $Logger->write('My log message!');
  • 18. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 18 class Logger { protected static $_instance; private function __construct($options = null) {} public static function &getInstance($options = null) { if (is_null(self::$_instance)) { self::$_instance = new self($options); } return self::$_instance; } protected function _write($message, $type = null) {} public static function write($message, $type = null) { $_this = self::getInstance(); $_this->_write($message, $type = null); } } Logger::write('My log message!');
  • 19. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 19 Order the factory to get your favorite jeans Factory MethodFactory Method
  • 20. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 20 Factory Method - Design Pattern ● Single interface for creating instance from a family of classes that can do the same task in multiple ways ● Reduce platform dependency ● Example: ● Database Driver – mysqli, sqlite, oracle, postgres, odbc, mssql ● Authentication – Database, LDAP, OpenID etc
  • 21. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 21 class DatabaseDriver { static function &factory($driver = null, $options = null) { switch ($driver) { case 'postgres': return PostgresDriver($options); case 'sqlite': return SQLiteDriver($options); default: return MySQLiDriver($options); } } } $DbDriver = DatabaseDriver::factory('mysqli');
  • 22. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 22 MVC - Design Patterns ● Separate presentation, decision making and data layer ● Web is MVC ● So, your web application should be ● Zend Framework, CakePHP, CodeIgniter all are MVC StorageClient Server
  • 23. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 23 ORM – Object Relational Mapping ● Raw SQL? No more! ● ORM is more flexible, efficient and maintainable ● CakePHP has built-in ORM through association ● Zend has Relationships using Zend_Db_Table ● Doctrine and Propel are most popular ORM in PHP ● Doctrine can be used with both Zend Framework & CodeIgniter
  • 24. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 24 Abstract Class ● Incomplete implementation of some concept ● You can implement multiple Interfaces but extend from only one abstract class ● You can't create instance of an Abstract Class ● Type hinting, enforce object type
  • 25. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 25 Code Reuse
  • 26. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 26 Code Reuse – when and how? ● Don't Re-Invent the Wheel ● But, you can always Improve the Wheel ● Decide when to Reuse ● Got a peace of code that can perform a specific task individually ● No copy & paste of the same code, put them inside a wrapper class and call whenever you need.
  • 27. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 27 Wrap your code ● Say you have got a piece of code for updating Twitter Status ● First, separate configuration variable like apiUrl, username and password ● Separate variables that are specific to call, like message ● Write your update method class Twitter { protected $_configs = array( 'apiUrl' => '_api_url_', 'username' => '', 'password' => '' ); function __construct($options) { $this->_configs = $options; } function setConfig($options); function update($message); }
  • 28. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 28 Avoid DependencyAvoid Dependency ● My belief “Always keep the door open” ● Loosely coupled classes are reusable ● Make your class independent and flexible as much as you can ● Avoid dependency on global variables, constants, files, paths, system parameters ● Use dependency injection if necessary
  • 29. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 29 Share Your Code ● Your Blog ● PHPClasses.org ● Google Code ● Github.com
  • 30. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 30 Question and Answer ?
  • 31. phpXperts 2010 Md. Rayhan Chowdhury | ray@raynux.com 31 Source ● All images are taken from flickr.com