Expert PHP 5 Tools - Dirk Merkel - E-Book

Expert PHP 5 Tools E-Book

Dirk Merkel

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Even if you find writing PHP code easy, writing code that is efficient and easy to maintain and reuse is not so straightforward. Self-taught PHP developers and programmers transitioning from other languages often lack the knowledge to work with PHP on an enterprise level. They need to take their PHP development skills to that level by learning the skills and tools necessary to write maintainable and efficient code.This book will enable you to take your PHP development skills to an enterprise level by teaching you the skills and tools necessary to write maintainable and efficient code. You will learn how to perform activities such as unit testing, enforcing coding standards, automating deployment, and interactive debugging using tools created for PHP developers – all the information in one place. Your code will be more maintainable, efficient, and self-documented.From the design phase to actually deploying the application, you will learn concepts and apply them using the best-of-breed tools available in PHP.Experienced developers looking for expertise in PHP development will learn how to follow best practices within the world of PHP. The book contains many well-documented code samples and recipes that can be used as a starting point for producing quality code.Specifically, you will learn to design an application with UML, code it in Eclipse with PDT, document it with phpDocumentor, debug it interactively with Xdebug, test it by writing PHPUnit tests, manage source code in Subversion, speed up development and increase stability by using Zend Framework, pull everything together using continuous integration, and deploy the application automatically with Phing – all in one book. The author's experience in PHP development enables him to share insights on using enterprise tools, in a clear and friendly way.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 522

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Expert PHP 5 Tools
Credits
About the Author
About the Reviewers
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code for the book
Errata
Piracy
Questions
1. Coding Style and Standards
Coding standard considerations
Pros
Cons
A PHP coding standard
Formatting
PHP tags
Indenting
Line length
Line endings
Spacing
Statements
Strings
Arrays
Control structures
If-elseif-else statements
Switch statements
Class and method definitions
Naming conventions
Class names
Property and variable names
Constant names
Method and function names
Methodology
Type hinting
Separating object creation from initialization
Class files
Class names and directory structures
Visibility and access
Including source files
Comments
Inline documentation
Coding standard adherence and verification
PHP_CodeSniffer for automated checking
Installing PHP_CodeSniffer
Basic usage
Slightly advanced usage
Validating against your own coding standard
Creating the directories
The main coding standard class file
Creating Sniffs
Tokenization
Writing our first sniff
Extending existing sniffs
Automated code checks
Summary
2. Documentation with phpDocumentor
Code-level documentation
Levels of detail
Introducing phpDocumentor
Installing phpDocumentor
DocBlocks
Short and long descriptions
Tags
DocBlock templates
Tutorials
Naming conventions and how to reference tutorials
DocBook syntax
Documenting a project
Documentation without DocBlocks
Documentation with DocBlocks
phpDocumentor options
Command line reference
Config files
Browser-based interface
Tag reference
Standard tags
@access
@author
@category
@copyright
@deprecated
@example
@filesource
@global
@ignore
@internal
@license
@link
@method
@name
@package
@property
@return
@see
@since
@static
@staticvar
@subpackage
@todo
@tutorial
@uses
@var
@version
Inline tags
{@Example}
{@id}
{@internal}}
{@inheritdoc}
{@link}
{@source}
{@toc}
{@tutorial}
PHP4 elements
Custom tags
Summary
3. The Eclipse Integrated Development Environment
Why Eclipse?
Introducing PDT
Installing Eclipse
Requirements
Choosing a package
Adding the PDT plugin
Basic Eclipse concepts
Workspace
Views
Perspectives
A PDT sample project
PDT features
Editor
Syntax highlighting
Code assist
Code folding
Mark occurrences
Override indicators
Type, method, and resource navigation
Inspection
Projects and files
PHP explorer
Type hierarchy
Debugging
PDT preferences
Appearance
Code style
Formatter
Code templates
Debug
Installed debuggers
Step filtering
Workbench options
Editor
Code assist
Code folding
Hovers
Mark occurrences
Save actions
Syntax coloring
Task tags
Typing
New project layout
PHP executables
PHP interpreter
PHP manual
PHP servers
Templates
Other features
PHP function reference
Eclipse plugins
Zend Studio for Eclipse
Support
Refactoring
Code generation
PHPUnit testing
PhpDocumentor support
Zend Framework integration
Zend server integration
Summary
4. Source Code and Version Control
Common use cases
A brief history of source code control
CVS
Introducing Subversion
Client installation
Server configuration
Apache with mod_dav_svn
svnserve
Subversion concepts
Repository
Tags
Trunk
Branches
Working (Local) copy
Merging
Revisions and versions
Updating
Comparing
History/Log
Annotating code
Reverting
Committing
Subversion command reference
svn
blame
cat
changelist
checkout
cleanup
commit
copy
delete
diff
export
help
import
info
list
lock
log
merge
mergeinfo
mkdir
move
propdel
propedit
propget
proplist
propset
resolve
resolved
revert
status
switch
unlock
update
svnadmin
create
dump
svnlook
svnserve
svndumpfilter
svnversion
Creating a Subversion project
Basic version control workflow
A closer look at the repository
Data store
Layout
Branching and merging
What is a branch?
Why branch?
How to branch?
Maintaining and merging a branch
Branching workflow
UI clients
Eclipse plug-ins
TortoiseSVN
WebSVN
Subversion conventions and best practices
Customizing Subversion
Hooks
Enforcing coding standards with a pre-commit hook
Notifying developers of commits with a post-commit hook
Summary
5. Debugging
First line of defense: syntax check
Logging
Configuration options
Customizing and controlling config options: PhpIni
PhpIni example
Outputting debug information
Functions
echo(string $arg1 [, string $... ] / print(string $arg)
var_dump(mixed $expression [, mixed $expression [, $... ]]) and print_r(mixed $expression [, bool $return= false ])
highlight_string(string str [, bool return]) and highlight_file(string filename [, bool return])
get_class([object object])
get_object_vars(object object)
get_class_methods(mixed class_name)
get_class_vars(string class_name)
debug_backtrace()
debug_print_backtrace()
exit([string status]) or exit (int status)
Magic constants
Writing our own debugging class
Functional requirements
DebugException
Using DebugException
DebugException: Pros and cons
Introducing Xdebug
Installing Xdebug
Configuring Xdebug
Immediate benefits
var_dump() improved
var_dump() settings
Errors and exceptions beautified
Stack trace settings
Protection from infinite recursion
Remote debugging
Remote server debug configuration
Debugging client configuration
Summary
6. PHP Frameworks
Writing your own framework
Evaluating and choosing frameworks
Community and acceptance
Feature road map
Documentation
Code quality
Coding standards and compliance
Project fit
Easy to learn and adapt
Open source
Familiarity
Their rules
Popular PHP frameworks
Zend
CodeIgniter
Symfony
Yii
Zend Framework application
Feature list
Application skeleton
Important concepts
Bootstrapping
MVC
Application structure detail
Model: application/models/
View: application/views/
Controller: application/controllers/
Configuration: application/configs/
Library
Public
Tests
Enhancements
Adding a layout
Adding views
Adding logging
Adding a database
Adding a model
Adding a controller
Putting it all together
Summary
7. Testing
Testing methods
Black box
White box
Gray box
Types of testing
Unit testing
Integration testing
Regression testing
System testing
User acceptance testing
Introducing PHPUnit
Installing PHPUnit
String search project
BMH algorithm basics
Implementing BMH
Unit testing BoyerMooreStringSearch
The test class
Assertions
Organization
Our first unit test
Extended test class features
Fixtures
Annotations
Data providers
Exceptions
Automation: generating tests from classes
Unimplemented and skipped tests
Automation: generating classes from tests
Test-driven development
Enhancing our example with TDD
Code coverage
TestCase subclasses
Summary
8. Deploying Applications
Goals and requirements
Deploying your application
Checking out and uploading files
Displaying an under-maintenance message
Upgrading and installing files
Upgrading database schema and data
Rotating log files and updating symbolic links
Verifying the deployed application
Automating deployment
Phing
Installing Phing
Basic syntax and file structure
Tasks
Targets
Properties and property files
Types
Filters
Mappers
The project tag
Deploying a site
Separating external dependencies
Creating a build script
Environment and properties
Directory skeleton
Subversion export and checkout
Building files from templates
Maintenance page
Database backup
Database migrations
Going live
Putting it all together
Backing out
Summary
9. PHP Application Design with UML
Meta-model versus notation versus our approach
Levels of detail and purpose
Round-trip and one-way tools
Basic types of UML diagrams
Diagrams
Class diagrams
Elements of a class
Properties (Attributes)
Methods (Operations)
Static methods and properties
A class diagram example
Relationships
Association
Aggregation
Composition
Dependency
Generalization
Interfaces
Example refactored
Code generators
Sequence diagrams
Scope
A sequence diagram of the network scanner
Objects and lifelines
Methods
Creating and destroying object
Loops and conditionals
Synchronous versus asynchronous calls
Use cases
Use cases — diagrams optional
When to create use cases
Example use case
Background
Typical scenario
Example use case diagram
Actors
System boundary
Use cases
Relationships
Summary
10. Continuous Integration
The satellite systems
Version control: Subversion
Commit frequency
Testing: PHPUnit
Automation: Phing
Coding style: PHP_CodeSniffer
Documentation: PhpDocumentor
Code coverage: Xdebug
Environment setup considerations
Do I need a dedicated CI server?
Do I need a CI tool?
CI tools
XINC (Xinc Is Not CruiseControl)
phpUnderControl
Continuous integration with phpUnderControl
Installation
Installing CruiseControl
Installing phpUnderControl
Overlaying CruiseControl with phpUnderControl
CruiseControl configuration
Overview of the CI process and components
CruiseControl and project layout
Getting the project source
Configuring the project: build.xml
Configuring CruiseControl
Advanced options
Bootstrappers
Publishers
Running CruiseControl
The overview page
The tests page
Metrics
Coverage
Documentation
CodeSniffer
PHPUnit PMD
Replacing Ant with Phing
Summary
Index

Expert PHP 5 Tools

Dirk Merkel

Expert PHP 5 Tools

Copyright © 2010 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: April 2010

Production Reference: 1240310

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-847198-38-9

www.packtpub.com

Cover Image by Karl Swedberg (<[email protected]>)

Credits

Author

Dirk Merkel

Reviewers

Andrew J. Peterson

Deepak Vohra

Acquisition Editor

Douglas Paterson

Development Editor

Ved Prakash Jha

Technical Editor

Neha Damle

Indexer

Monica Ajmera

Editorial Team Leader

Gagandeep Singh

Project Team Leader

Lata Basantani

Project Coordinator

Joel Goveya

Proofreader

Claire Cresswell-Lane

Graphics

Geetanjali Sawant

Production Coordinator

Shantanu Zagade

Melwyn D'sa

Cover Work

Melwyn D'sa

About the Author

Dirk Merkel has been developing software in a variety of programming languages for many years, including PHP, Java, Perl, and Ruby. His focus has been on web-related technologies and he has over 10 years experience coding in PHP. He has experience covering the whole software development cycle and has been managing several teams of developers working on large-scale projects.

He has been working as a professional consultant through his company Waferthin Web Works LLC (http://www.waferthin.com) and can be reached at <[email protected]>. He is also the Chief Technology Officer at VivanTech Inc., a San Diego based provider of IT solutions.

He has written several articles on software development and security. Expert PHP 5 Tools is his first book.

He lives in San Diego with his lovely wife and two wonderful daughters.

I would like to thank my family (near and far) — especially my parents and sisters, my lovely wife, Rania, and my two awesome daughters, Nadia and Yasmin.

About the Reviewers

Andrew J. Peterson lives with his wife and three daughters in San Francisco, California. He has 20 years experience building and managing software systems for consumers, enterprises, start-ups, and non-profits. He brings expertise in the full life-cycle of software development, engineering, methodologies, architecture, and usability. He has diverse experience in the industry. In the consumer space, he led a team in the creation of the top-selling SoundEdit 16. He served numerous roles producing enterprise software, for the leading supplier of software solutions for container terminals, shipping ports and lines, and distribution centers. Over the past ten years, he transferred this experience to web-based software. He has built a variety of web applications, including non-profit, social networking, social search, pharmaceuticals and social ecommerce. He has build successful projects in a variety of languages, including Java, Ruby, C++, Ruby and Perl.

In the primal days of the Web, he wrote a manual helping users connect their Macintosh to the Web. More recently, he reviewed PHP and Scriptaculous Web Application Interfaces for Packt Publishing.

I'd like to thank my wife for the bliss she brings.

Deepak Vohra is a consultant and a principal member of the NuBean.com software company. Deepak is a Sun Certified Java Programmer and Web Component Developer, and has worked in the fields of XML and Java programming and J2EE for over five years. Deepak is the co-author of the Apress book Pro XML Development with Java Technology and was the technical reviewer for the O'Reilly book WebLogic: The Definitive Guide. Deepak was also the technical reviewer for the Course Technology PTR book Ruby Programming for the Absolute Beginner, and the technical editor for the Manning Publications book Prototype and Scriptaculous in Action. Deepak is also the author of the Packt Publishing books JDBC 4.0 and Oracle JDeveloper for J2EE Development and Processing XML Documents with Oracle JDeveloper 11g.

Preface

This book will enable you to take your PHP development skills to an enterprise level by teaching the skills and tools necessary to write maintainable and efficient code. You will learn how to perform activities such as unit testing, enforcing coding standards, automating deployment, and interactive debugging using tools created for PHP developers — all the information in one place. Your code will be more maintainable, efficient, and self-documenting.

What this book covers

Chapter 1, Coding Style and Standards, explains how to define a coding standard that suits your development process and how to enforce it using PHP_CodeSniffer.

Chapter 2, Documentation with phpDocumentor, explains how to properly document your code with phpDocumentor and generate well formatted developer documentation.

Chapter 3, The Eclipse Integrated Development Environment, explains how to install, customize, and use the free PDT plug-in for Eclipse to create a powerful IDE for PHP development

Chapter 4, Source Code and Version Control, explores the ins and outs of subversion for distributed version control for development teams. It also teaches you to extend subversion functionality with PHP scripts.

Chapter 5, Debugging, teaches you to write your own flexible debugging library and master remote interactive debugging with Xdebug.

Chapter 6, PHP Frameworks, explains how to evaluate, compare, and choose frameworks that suit your projects and development style. Master the most commonly used modules of Zend Framework.

Chapter 7, Testing, explains testing methods and types, unit testing, creating comprehensive test suites with PHPUnit, and test-driven development.

Chapter 8, Application Deployment, states guidelines for automated and reversible application deployment, automating upgrades and deployments with Phing

Chapter 9, PHP Application Design with UML, introduces the reader to UML, class diagrams, sequence diagrams, and use cases.

Chapter 10, Continuous Integration, explains how to use CI, keep costs down and save time by discovering bugs and conflicts in your projects, at an early stage.

What you need for this book

To follow along with the examples, you will need a working version of PHP 5 installed on your system. Some of the chapters rely on command line tools such as pear and pecl, which are included in the standard distribution of PHP. Version 5.2.x of PHP or higher is recommended for maximum compatibility with the sample code. If you do not already have PHP installed on your system, you can download it from php.net here:

http://www.php.net/downloads.php

Although this book was written and coded on OS X, any flavor of MS Windows or Linux will do the job as well. Basic familiarity with your system's command line and a handy text editor for tweaking the examples will also be helpful.

Who this book is for

This book has been written for professional developers new to PHP and experienced PHP developers, who want to take their skills to the next level by learning enterprise level tools and techniques.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "We can include other contexts through the use of the include directive."

A block of code will be set as follows:

<fileset dir="${project.home}/build" > <include name="*.properties" /> <exclude name="deprecated.properties" /> </fileset>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items will be shown in bold:

<fileset dir="${project.home}/build" > <include name="*.properties" /> <exclude name="deprecated.properties" /> </fileset>

Any command-line input or output is written as follows:

$ phing upgrade-db

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: "clicking the Next button moves you to the next screen".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book — what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply drop an email to <[email protected]>, and mention the book title in the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code for the book

Visit http://www.packtpub.com/files/code/8389_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.

Errata

Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books — maybe a mistake in text or code — we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Coding Style and Standards

A developer's coding style takes time to develop and often reflects his or her personality. Consequently, you are likely to encounter more than just a little resistance when trying to get your team members to adopt a different style. However, that is exactly what I will be arguing in this chapter. We will learn about the benefits of standardizing on a certain coding style. Along the way, we will develop our own style and learn how to automatically enforce that or any standard of your choice using the handy PHP_CodeSniffer utility. I am hoping that at the end of this chapter, you will be able to take a look at your own and your co-workers' coding styles and make the necessary changes to reap the benefits that include code readability and maintainability.

Coding standard considerations

Since you are reading this book, there is a good chance that you have a couple of years of programming experience under your belt. Even if it is in a programming language other than PHP, you have probably had plenty of time to develop your own style of writing code. In all likelihood, you have chosen or developed a style that appears to make the most sense to you and that you can adhere to and read easily.

However, if you are reading this book, it also means that you are looking to improve your knowledge of PHP. Consequently, I assume that you are willing to change your coding style or at least fine-tune it. First, let me try to convince you that this is worth the effort.

Even if you are writing code only for yourself and have no reasonable expectation that any other programmer will ever look at or work on it, you will probably want to follow your own coding standards. Whether you are aware of it or not, chances are you are doing this already. For example, at some point every programmer decides whether to put the opening brackets on the same line or the one following the if-statement. I would also guess that you are doing it the same way every time.

Personally, I have had many occasions to revisit code that I had written years ago. I can always tell how well defined my coding style was at the time. The more consistent the style, the easier it is to get back into the code and understand the intricacies of what it is doing.

I think we have all had trouble understanding our own code after not looking at it for a while. If you haven't been in that position already, imagine inheriting a project of substantial size and having to get used to someone else's coding habits and oddities. This is where agreeing on a common coding standard pays off. If all developers working on the same project agree on the same standard, collaboration becomes so much easier as it takes less time to find and figure things out. I'm not just talking about where to place the opening brackets, but rather things such as locations of classes and libraries, names of methods and attributes, and inline documentation.

Let's consider some of the pros and cons of having formally defined coding standards — starting with the pros.

Pros

It will be easier to understand code. Whether you are looking at your own code or that of another development team member, reading and understanding the code will be more fluent. This benefit extends not only to current contributors, but also to programmers who are new to the team or PHP in general. Not having to grapple with different styles and conventions will allow them to come up to speed more quickly and allow them to absorb the common style from the beginning.

Nowadays, software is often designed, developed, tested, and used in a distributed fashion. Team members could be located anywhere in the world. With todays tools for communication, the rules for where and how to assemble software teams are being rewritten. Just take a look at some of the very successful Open Source projects, many of which have no physical presence at all. Consider the Apache Software Foundation or in the PHP space, the Zend Framework project, both of which are very successful examples of highly successful projects with many distributors from all over the globe. Projects such as these are some prime candidates for reaping the benefits of a common coding standard.

I would go so far as to say that the right coding standard should go beyond style. It can improve the quality and robustness of the code. For example, having developers consistently validate method parameters will undoubtedly result in a more robust code base.

Cons

Developers tend to ignore coding standards. Adhering to a common standard requires everyone to change their ways some more so, some less. Unless someone takes on the responsibility of enforcing the standard, change is not going to come about by itself. When developers are too set in their ways or push back when being asked to change, you run the risk of alienating them. The best thing is to get everyone involved in developing the standard. With their own time and expertise invested in the project, they are more likely to abide by the rules the group agreed on.

There are also some common myths when it comes to coding standards in general. First, people tend to think that it stifles creativity. What people who are not familiar or experienced with software development often don't realize is that software is as much a creative process as writing a poem or composing a melody is. There are basic rules to follow in all those endeavors. Depending on what kind of poem you are writing, you might have to make sure it rhymes, follows a certain rhythm, or only has a certain number of syllables. Writing software is no different. At a basic level, you have some rules to define the playing field. Having a coding standard is just a small part of the rules. There are still endless possibilities for the developer to express his creativity and ingenuity.

The second myth you commonly encounter is that it is unnecessary. You will often hear programmers say something like: "My code has been working flawlessly all along. Why do I need a coding standard?" or "If you can't understand the code I write, then you're not good enough to work on this project."

The former statement misses the point. A coding standard's primary purpose is not to make the code work (although it may help). There are many other tools available to help developers with that part of their work. What a coding standard does is make it easier and faster for the developer to understand their own and others' code.

The latter statement betrays the developer's attitude towards working in a group environment. In my opinion, exactly the opposite is true. The bigger the development team and the more complex the project, the more it can benefit from some common ground rules.

Summary