SlideShare a Scribd company logo
1 of 60
Download to read offline
Building and deploying PHP applications
               with Phing

                Michiel Rook

            PHP UK Conference 2012
About me


  • Freelance PHP & Java contractor / consultant

  • PHP since ’99

  • Phing project lead

  • http://www.linkedin.com/in/michieltcs

  • @michieltcs




                                    Building and deploying PHP applications with Phing
This Talk


  • Why use a build tool

  • What is Phing

  • Usage

  • Various examples

  • Extending Phing




                           Building and deploying PHP applications with Phing
Why Use A Build Tool?
Why Use A Build Tool




                                 Repetition
              http://www.flickr.com/photos/andrewmalone/5162632817/




                                           Building and deploying PHP applications with Phing
Repetition


  • We are human

  • We get bored

  • We forget things

  • We make mistakes




                       Building and deploying PHP applications with Phing
Repetition


  • Version control

  • (Unit) Testing

  • Configuring

  • Packaging

  • Uploading

  • DB changes

  • ...




                      Building and deploying PHP applications with Phing
Repetition


  • Version control

  • (Unit) Testing

  • Configuring

  • Packaging

  • Uploading

  • DB changes

  • ...

  • Boring!




                      Building and deploying PHP applications with Phing
Why Use A Build Tool




                                 Automate!
               http://www.flickr.com/photos/patrick_h/6209981673/




                                          Building and deploying PHP applications with Phing
Automate!


  • Developers, testers, administrators...

  • Easier handover to new team members

  • Improves quality

  • Reduces errors

  • Saves time

  • Consolidate scripts, reduce technical debt




                                       Building and deploying PHP applications with Phing
What Is Phing




                http://www.flickr.com/photos/canucksfan604/5471322484/


                                             Building and deploying PHP applications with Phing
What Is Phing


  • PHing Is Not GNU make; it’s a PHP project build system or build tool
    based on Apache Ant.

  • Originally developed by Binarycloud

  • Ported to PHP5 by Hans Lellelid

  • 2004: my first commit

  • 2009: lead




                                      Building and deploying PHP applications with Phing
What Can Phing Do


  • Scripting using XML build files

  • Human readable

  • Mostly cross-platform

  • Minimal dependencies

  • Interface to various popular (PHP) tools




                                      Building and deploying PHP applications with Phing
What Can Phing Do


  • Scripting using XML build files

  • Human readable

  • Mostly cross-platform

  • Minimal dependencies

  • Interface to various popular (PHP) tools

  • ”Good glue”




                                      Building and deploying PHP applications with Phing
What Can Phing Do




                    Building and deploying PHP applications with Phing
Why Use Phing


  • Ant?

  • Rich set of tasks

  • Integration with PHP specific tools

  • Allows you to stay in the PHP infrastructure

  • Easy to extend

  • Embed PHP code directly in the build file




                                      Building and deploying PHP applications with Phing
The Basics
Installing Phing

  • PEAR installation

    $ pear channel-discover pear.phing.info
    $ pear install [--alldeps] phing/phing

  • Optionally, install the documentation package

    $ pear install phing/phingdocs




                                     Building and deploying PHP applications with Phing
Build Files


  • Phing uses XML build files

  • Contain standard elements

       • Task: code that performs a specific function (svn checkout,
         mkdir, etc.)
       • Target: groups of tasks, can optionally depend on other targets
       • Project: root node, contains multiple targets




                                      Building and deploying PHP applications with Phing
Example Build File

  <project name="Example" default="world">
      <target name="hello">
          <echo>Hello</echo>
      </target>

      <target name="world" depends="hello">
          <echo>World!</echo>
      </target>
  </project>

   Buildfile: /home/michiel/phing/simple.xml

   Example > hello:

        [echo] Hello

   Example > world:

        [echo] World!

   BUILD FINISHED



                                      Building and deploying PHP applications with Phing
Properties

  • Simple key-value files (.ini)

  ## build.properties
  version=1.0

  • Can be expanded by using ${key} in the build file

  $ phing -propertyfile build.properties ...

  <project name="Example" default="default">
      <target name="default">
          <property file="build.properties" />

          <echo>${version}</echo>
      </target>
  </project>




                                    Building and deploying PHP applications with Phing
Filesets

  • Constructs a group of files to process

  • Supported by most tasks

   <fileset dir="./application" includes="**"/>

   <fileset dir="./application">
       <include name="**/*.php" />
       <exclude name="**/*Test.php" />
   </fileset>

  • References: define once, use many

   <fileset dir="./application" includes="**" id="files"/>

   <fileset refid="files"/>




                                     Building and deploying PHP applications with Phing
Filesets

  • Selectors allow fine-grained matching on certain attributes

  • contains, date, file name & size, ...

   <fileset dir="${dist}">
       <and>
           <filename name="**"/>
           <date datetime="01/01/2011" when="before"/>
       </and>
   </fileset>




                                       Building and deploying PHP applications with Phing
Mappers & Filters


  • Transform files during copy/move/...

  • Mappers

      • Change filename
      • Flatten directories

  • Filters

      • Strip comments, white space
      • Replace values
      • Perform XSLT transformation
      • Translation (i18n)




                                      Building and deploying PHP applications with Phing
Mappers & Filters

  <copy todir="${build}">
      <fileset refid="files"/>
      <mapper type="glob" from="*.txt" to="*.new.txt"/>
      <filterchain>
          <replaceregexp>
              <regexp pattern="rn" replace="n"/>
              <expandproperties/>
          </replaceregexp>
      </filterchain>
  </copy>




                                  Building and deploying PHP applications with Phing
Examples
Examples


  • Version control

  • Unit testing

  • Packaging

  • Deployment

  • Database migration

  • Continuous integration




                             Building and deploying PHP applications with Phing
Version Control

  • (CVS), SVN, Git

  <svncopy
     username="michiel"
     password="test"
     repositoryurl="svn://localhost/phing/trunk/"
     todir="svn://localhost/phing/tags/1.0"/>

  <svnexport
     repositoryurl="svn://localhost/project/trunk/"
     todir="/home/michiel/dev"/>

  <svnlastrevision
     repositoryurl="svn://localhost/project/trunk/"
     propertyname="lastrev"/>
  <echo>Last revision: ${lastrev}</echo>




                                  Building and deploying PHP applications with Phing
PHPUnit

  • Built-in support for most configuration options

  • Gathers code coverage information

  • Various output formats (JUnit / Clover)

  • Reporting (JUnit style)




                                      Building and deploying PHP applications with Phing
PHPUnit Example

  • Stop the build when a test fails

  <phpunit haltonfailure="true" haltonerror="true"
      bootstrap="my_bootstrap.php" printsummary="true">
      <batchtest>
          <fileset dir="src">
              <include name="**/*Test.php"/>
          </fileset>
      </batchtest>
  </phpunit>

   Buildfile: /home/michiel/phpunit/build.xml

   Demo > test:

     [phpunit] Total tests run: 1, Failures: 1, Errors: 0,
         Incomplete: 0, Skipped: 0, Time elapsed: 0.00591 s
   Execution of target "test" failed for the following reason:
   /home/michiel/phpunit/build.xml:3:44: Test FAILURE (testSayHello in
   class HelloWorldTest): Failed asserting that two strings are equal.




                                       Building and deploying PHP applications with Phing
PHPUnit Example

  • Determine which files to include in the coverage report

  <coverage-setup database="reports/coverage.db">
      <fileset dir="src">
          <include name="**/*.php"/>
          <exclude name="**/*Test.php"/>
      </fileset>
  </coverage-setup>

  • Gather code coverage and other data during the test run

  <phpunit codecoverage="true">
      <formatter type="xml" todir="reports"/>
      <batchtest>
          <fileset dir="src">
              <include name="**/*Test.php"/>
          </fileset>
      </batchtest>
  </phpunit>



                                     Building and deploying PHP applications with Phing
PHPUnit Example

  • Generate some reports

  <phpunitreport infile="reports/testsuites.xml"
      format="frames" todir="reports/tests"/>
  <coverage-report outfile="reports/coverage.xml">
      <report todir="reports/coverage" title="Demo"/>
  </coverage-report>




                                  Building and deploying PHP applications with Phing
Documentation

  • Phing currently integrates with popular documentation tools

      • DocBlox
      • PhpDocumentor
      • ApiGen

  • Also supports r(e)ST (reStructuredText)

  <docblox title="Phing API Documentation"
      output="docs" quiet="true">
      <fileset dir="../../classes">
          <include name="**/*.php"/>
      </fileset>
  </docblox>




                                     Building and deploying PHP applications with Phing
DocBlox




          Building and deploying PHP applications with Phing
Packaging

  • Create bundles or packages

  • Phing supports most popular formats: tar (pear), zip, phar

  <pearpkg name="demo" dir=".">
      <fileset refid="files"/>

      <option   name="outputdirectory" value="./build"/>
      <option   name="description">Test package</option>
      <option   name="version" value="0.1.0"/>
      <option   name="state" value="beta"/>

      <mapping name="maintainers">
          <element>
              <element key="handle" value="test"/>
              <element key="name" value="Test"/>
              <element key="email" value="test@test.nl"/>
              <element key="role" value="lead"/>
          </element>
      </mapping>
  </pearpkg>

                                      Building and deploying PHP applications with Phing
Packaging - TAR / ZIP

   <tar compression="gzip" destFile="package.tgz"
       basedir="build"/>

   <zip destfile="htmlfiles.zip">
       <fileset dir=".">
           <include name="**/*.html"/>
       </fileset>
   </zip>




                                   Building and deploying PHP applications with Phing
Packaging - PHAR

  <pharpackage
          compression="gzip"
          destfile="test.phar"
          stub="stub.php"
          basedir=".">
          <fileset dir="hello">
                  <include name="**/**" />
          </fileset>
          <metadata>
                  <element name="version" value="1.0" />
                  <element name="authors">
                          <element name="John Doe">
                                  <element name="e-mail"
                                  value="john@example.com" />
                          </element>
                  </element>
          </metadata>
  </pharpackage>




                                  Building and deploying PHP applications with Phing
Putting it all together - deployments
Copying to a server

  • SSH

  <scp username="john" password="smith"
      host="webserver" todir="/www/htdocs/project/">
      <fileset dir="test">
          <include name="*.html"/>
      </fileset>
  </scp>

  • FTP

  <ftpdeploy
      host="server01"
      username="john"
      password="smit"
      dir="/var/www">
      <fileset dir=".">
          <include name="*.html"/>
      </fileset>
  </ftpdeploy>

                                     Building and deploying PHP applications with Phing
Symbolic links

  • All releases stored in ”backup” directory

  • Symlink application directory to latest release (similar to Capistrano)

  • Allows for easy (code) rollbacks

  <svnlastrevision repositoryurl="${deploy.svn}"
      property="deploy.rev"/>

  <svnexport repositoryurl="${deploy.svn}"
      todir="/www/releases/build-${deploy.rev}"/>

  <symlink target="/www/releases/build-${deploy.rev}"
      link="/www/current"/>

  • Also on a remote server

  <ssh host="webserver" command="ln -s
      /www/releases/build-${deploy.rev} /www/current"/>



                                       Building and deploying PHP applications with Phing
Multiple servers / targets

  • Several deployment targets: testing, staging, production, ...

  • Keep one property file per target

  • Select property file based on input

   <input propertyname="env"
           validargs="testing,staging,production">
   Enter environment name
   </input>

   <property file="${env}.properties"/>

   <ssh host="${deploy.host}" command="..."/>




                                       Building and deploying PHP applications with Phing
Database Migration

  • Set of delta SQL files (1-create-post.sql)

  • Tracks current version of your db in changelog table

  • Generates do and undo SQL files

  CREATE TABLE changelog (
    change_number BIGINT NOT NULL,
    delta_set     VARCHAR(10) NOT NULL,
    start_dt      TIMESTAMP NOT NULL,
    complete_dt   TIMESTAMP NULL,
    applied_by    VARCHAR(100) NOT NULL,
    description   VARCHAR(500) NOT NULL
  )




                                      Building and deploying PHP applications with Phing
Database Migration

  • Delta scripts with do (up) & undo (down) parts

  --//

  CREATE TABLE ‘post‘ (
      ‘title‘ VARCHAR(255),
      ‘time_created‘ DATETIME,
      ‘content‘ MEDIUMTEXT
  );

  --//@UNDO

  DROP TABLE ‘post‘;

  --//




                                     Building and deploying PHP applications with Phing
Database Migration

  <dbdeploy
      url="sqlite:test.db"
      dir="deltas"
      outputfile="deploy.sql"
      undooutputfile="undo.sql"/>

  <pdosqlexec
      src="deploy.sql"
      url="sqlite:test.db"/>

   Buildfile: /home/michiel/dbdeploy/build.xml

   Demo > migrate:

    [dbdeploy] Getting applied changed numbers from DB:
        mysql:host=localhost;dbname=demo
    [dbdeploy] Current db revision: 0
    [dbdeploy] Checkall:
   [pdosqlexec] Executing file: /home/michiel/dbdeploy/deploy.sql
   [pdosqlexec] 3 of 3 SQL statements executed successfully

   BUILD FINISHED


                                      Building and deploying PHP applications with Phing
Database Migration

  -- Fragment begins: 1 --
  INSERT INTO changelog
      (change_number, delta_set, start_dt, applied_by, description)
      VALUES (1, ’Main’, NOW(), ’dbdeploy’,
      ’1-create_initial_schema.sql’);
  --//

  CREATE TABLE ‘post‘ (
      ‘title‘ VARCHAR(255),
      ‘time_created‘ DATETIME,
      ‘content‘ MEDIUMTEXT
  );

  UPDATE changelog
      SET complete_dt = NOW()
      WHERE change_number = 1
      AND delta_set = ’Main’;
  -- Fragment ends: 1 --




                                  Building and deploying PHP applications with Phing
Database Migration

  -- Fragment begins: 1 --

  DROP TABLE ‘post‘;

  --//

  DELETE FROM changelog
                              WHERE change_number = 1
                              AND delta_set = ’Main’;
  -- Fragment ends: 1 --




                             Building and deploying PHP applications with Phing
Phing & Jenkins


  • Continuous integration

  • Phing plugin

  • Build periodically or after each commit

  • Verify and test the build

  • Deploy results




                                      Building and deploying PHP applications with Phing
Phing & Jenkins




                  Building and deploying PHP applications with Phing
Phing & Jenkins




                  Building and deploying PHP applications with Phing
Phing & Jenkins




                  Building and deploying PHP applications with Phing
Demonstration
Extending Phing
Extending Phing


  • Numerous extension points

      • Tasks
      • Types
      • Selectors
      • Filters
      • Mappers
      • Loggers
      • ...




                                Building and deploying PHP applications with Phing
Sample Task

  • Extends from Task

  • Contains main() method and optionally init()

  • Setter method for each attribute in the build file

  class SampleTask extends Task
  {
      private $var;

      public function setVar($v)
      {
          $this->var = $v;
      }

      public function main()
      {
          $this->log("value: " . $this->var);
      }
  }


                                       Building and deploying PHP applications with Phing
Sample Task

  • Use taskdef to make Phing aware of your new task

  <project name="Example" default="default">
      <taskdef name="sample"
          classpath="/dev/src"
          classname="tasks.my.SampleTask" />

      <target name="default">
          <sample var="Hello World" />
      </target>
  </project>




                                   Building and deploying PHP applications with Phing
Ad Hoc Extension

  • Define a task within your build file

  <target name="main">
      <adhoc-task name="foo"><![CDATA[
      class FooTest extends Task {
          private $bar;

           function setBar($bar) {
               $this->bar = $bar;
           }

           function main() {
               $this->log("In FooTest: " . $this->bar);
           }
      }
      ]]></adhoc-task>
      <foo bar="TEST"/>
  </target>




                                         Building and deploying PHP applications with Phing
Future Improvements


  • More tasks & support

  • Better performance

  • PHAR package (including popular dependencies)

  • More documentation

  • Increased test coverage

  • IDE support




                                  Building and deploying PHP applications with Phing
Future Improvements


  • More tasks & support

  • Better performance

  • PHAR package (including popular dependencies)

  • More documentation

  • Increased test coverage

  • IDE support

  • Pull requests! :-)




                                  Building and deploying PHP applications with Phing
Helpful Links


  • http://pear.php.net/

  • http://www.docblox-project.org/

  • http://www.dbdeploy.com/

  • http://www.jenkins-ci.org/

  • http://www.phing.info/docs/guide/stable/

  • http://github.com/phingofficial/phing




                               Building and deploying PHP applications with Phing
Questions?




             http://joind.in/4954

             http://www.phing.info

                #phing (freenode)

                  @phingofficial

                   Thank you!




                          Building and deploying PHP applications with Phing

More Related Content

What's hot

MySQL Audit 機制應用技術
MySQL Audit 機制應用技術MySQL Audit 機制應用技術
MySQL Audit 機制應用技術Jamie Lee
 
Async ... Await – concurrency in java script
Async ... Await – concurrency in java scriptAsync ... Await – concurrency in java script
Async ... Await – concurrency in java scriptAthman Gude
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinModern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinJava User Group Latvia
 
Spring MVC to iOS and the REST
Spring MVC to iOS and the RESTSpring MVC to iOS and the REST
Spring MVC to iOS and the RESTRoy Clarkson
 
Laravel - The PHP Framework for Web Artisans
Laravel - The PHP Framework for Web ArtisansLaravel - The PHP Framework for Web Artisans
Laravel - The PHP Framework for Web ArtisansWindzoon Technologies
 
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...Edureka!
 
Présentation html5
Présentation html5Présentation html5
Présentation html5Kénium
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications JavaAntoine Rey
 
Composer 經典食譜
Composer 經典食譜Composer 經典食譜
Composer 經典食譜Shengyou Fan
 
Learn nginx in 90mins
Learn nginx in 90minsLearn nginx in 90mins
Learn nginx in 90minsLarry Cai
 
Container Runtime Security with Falco
Container Runtime Security with FalcoContainer Runtime Security with Falco
Container Runtime Security with FalcoMichael Ducy
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python MeetupAreski Belaid
 

What's hot (20)

MySQL Audit 機制應用技術
MySQL Audit 機制應用技術MySQL Audit 機制應用技術
MySQL Audit 機制應用技術
 
Async ... Await – concurrency in java script
Async ... Await – concurrency in java scriptAsync ... Await – concurrency in java script
Async ... Await – concurrency in java script
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinModern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
 
Spring MVC to iOS and the REST
Spring MVC to iOS and the RESTSpring MVC to iOS and the REST
Spring MVC to iOS and the REST
 
Flask Basics
Flask BasicsFlask Basics
Flask Basics
 
GET and POST in PHP
GET and POST in PHPGET and POST in PHP
GET and POST in PHP
 
Laravel - The PHP Framework for Web Artisans
Laravel - The PHP Framework for Web ArtisansLaravel - The PHP Framework for Web Artisans
Laravel - The PHP Framework for Web Artisans
 
Git - Level 2
Git - Level 2Git - Level 2
Git - Level 2
 
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
Dockerfile Tutorial with Example | Creating your First Dockerfile | Docker Tr...
 
Présentation html5
Présentation html5Présentation html5
Présentation html5
 
Laravel Tutorial PPT
Laravel Tutorial PPTLaravel Tutorial PPT
Laravel Tutorial PPT
 
Git
GitGit
Git
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
 
Composer 經典食譜
Composer 經典食譜Composer 經典食譜
Composer 經典食譜
 
Php technical presentation
Php technical presentationPhp technical presentation
Php technical presentation
 
JavaScript Basic
JavaScript BasicJavaScript Basic
JavaScript Basic
 
Learn nginx in 90mins
Learn nginx in 90minsLearn nginx in 90mins
Learn nginx in 90mins
 
Nodejs buffers
Nodejs buffersNodejs buffers
Nodejs buffers
 
Container Runtime Security with Falco
Container Runtime Security with FalcoContainer Runtime Security with Falco
Container Runtime Security with Falco
 
Flask Introduction - Python Meetup
Flask Introduction - Python MeetupFlask Introduction - Python Meetup
Flask Introduction - Python Meetup
 

Similar to Building and deploying PHP applications with Phing

Automating Web Application Deployment
Automating Web Application DeploymentAutomating Web Application Deployment
Automating Web Application DeploymentMathew Byrne
 
Getting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalGetting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalPhilip Norton
 
Desktop Apps with PHP and Titanium
Desktop Apps with PHP and TitaniumDesktop Apps with PHP and Titanium
Desktop Apps with PHP and TitaniumBen Ramsey
 
Building and Deploying PHP apps with Phing
Building and Deploying PHP apps with PhingBuilding and Deploying PHP apps with Phing
Building and Deploying PHP apps with PhingMichiel Rook
 
Putting "Phings" together - how to automate your life
Putting "Phings" together - how to automate your lifePutting "Phings" together - how to automate your life
Putting "Phings" together - how to automate your lifeBoyan Borisov
 
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20Michael Lihs
 
Unit testing symfony plugins with php unit
Unit testing symfony plugins with php unitUnit testing symfony plugins with php unit
Unit testing symfony plugins with php unitChristian Schaefer
 
Stress Free Deployment - Confoo 2011
Stress Free Deployment  - Confoo 2011Stress Free Deployment  - Confoo 2011
Stress Free Deployment - Confoo 2011Bachkoutou Toutou
 
Build Your First SharePoint Framework Webpart
Build Your First SharePoint Framework WebpartBuild Your First SharePoint Framework Webpart
Build Your First SharePoint Framework WebpartEric Overfield
 
Introduction to PHP - SDPHP
Introduction to PHP - SDPHPIntroduction to PHP - SDPHP
Introduction to PHP - SDPHPEric Johnson
 
Professional PHP: an open-source alternative for enterprise development [Antw...
Professional PHP: an open-source alternative for enterprise development [Antw...Professional PHP: an open-source alternative for enterprise development [Antw...
Professional PHP: an open-source alternative for enterprise development [Antw...Combell NV
 
CodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.comCodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.comChristopher Cubos
 
Web development with Python
Web development with PythonWeb development with Python
Web development with PythonRaman Balyan
 
Symfony under control. Continuous Integration and Automated Deployments in Sy...
Symfony under control. Continuous Integration and Automated Deployments in Sy...Symfony under control. Continuous Integration and Automated Deployments in Sy...
Symfony under control. Continuous Integration and Automated Deployments in Sy...Max Romanovsky
 
Symfony Under Control by Maxim Romanovsky
Symfony Under Control by Maxim RomanovskySymfony Under Control by Maxim Romanovsky
Symfony Under Control by Maxim Romanovskyphp-user-group-minsk
 
Understanding SharePoint Framework Extensions
Understanding SharePoint Framework ExtensionsUnderstanding SharePoint Framework Extensions
Understanding SharePoint Framework ExtensionsBIWUG
 

Similar to Building and deploying PHP applications with Phing (20)

Automating Web Application Deployment
Automating Web Application DeploymentAutomating Web Application Deployment
Automating Web Application Deployment
 
Getting Started With Jenkins And Drupal
Getting Started With Jenkins And DrupalGetting Started With Jenkins And Drupal
Getting Started With Jenkins And Drupal
 
Desktop Apps with PHP and Titanium
Desktop Apps with PHP and TitaniumDesktop Apps with PHP and Titanium
Desktop Apps with PHP and Titanium
 
Building and Deploying PHP apps with Phing
Building and Deploying PHP apps with PhingBuilding and Deploying PHP apps with Phing
Building and Deploying PHP apps with Phing
 
Putting "Phings" together - how to automate your life
Putting "Phings" together - how to automate your lifePutting "Phings" together - how to automate your life
Putting "Phings" together - how to automate your life
 
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
Continuous Integration with Open Source Tools - PHPUgFfm 2014-11-20
 
Unit testing symfony plugins with php unit
Unit testing symfony plugins with php unitUnit testing symfony plugins with php unit
Unit testing symfony plugins with php unit
 
Stress Free Deployment - Confoo 2011
Stress Free Deployment  - Confoo 2011Stress Free Deployment  - Confoo 2011
Stress Free Deployment - Confoo 2011
 
Build Your First SharePoint Framework Webpart
Build Your First SharePoint Framework WebpartBuild Your First SharePoint Framework Webpart
Build Your First SharePoint Framework Webpart
 
Introduction to PHP - SDPHP
Introduction to PHP - SDPHPIntroduction to PHP - SDPHP
Introduction to PHP - SDPHP
 
Improving qa on php projects
Improving qa on php projectsImproving qa on php projects
Improving qa on php projects
 
Professional PHP: an open-source alternative for enterprise development [Antw...
Professional PHP: an open-source alternative for enterprise development [Antw...Professional PHP: an open-source alternative for enterprise development [Antw...
Professional PHP: an open-source alternative for enterprise development [Antw...
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
 
Php
PhpPhp
Php
 
CodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.comCodeIgniter - PHP MVC Framework by silicongulf.com
CodeIgniter - PHP MVC Framework by silicongulf.com
 
Web development with Python
Web development with PythonWeb development with Python
Web development with Python
 
Symfony under control. Continuous Integration and Automated Deployments in Sy...
Symfony under control. Continuous Integration and Automated Deployments in Sy...Symfony under control. Continuous Integration and Automated Deployments in Sy...
Symfony under control. Continuous Integration and Automated Deployments in Sy...
 
Symfony Under Control by Maxim Romanovsky
Symfony Under Control by Maxim RomanovskySymfony Under Control by Maxim Romanovsky
Symfony Under Control by Maxim Romanovsky
 
Understanding SharePoint Framework Extensions
Understanding SharePoint Framework ExtensionsUnderstanding SharePoint Framework Extensions
Understanding SharePoint Framework Extensions
 
Drupal8 for Symfony Developers
Drupal8 for Symfony DevelopersDrupal8 for Symfony Developers
Drupal8 for Symfony Developers
 

More from Michiel Rook

CQRS & Event Sourcing in the wild (ScotlandPHP 2016)
CQRS & Event Sourcing in the wild (ScotlandPHP 2016)CQRS & Event Sourcing in the wild (ScotlandPHP 2016)
CQRS & Event Sourcing in the wild (ScotlandPHP 2016)Michiel Rook
 
The road to continuous deployment (PHPCon Poland 2016)
The road to continuous deployment (PHPCon Poland 2016)The road to continuous deployment (PHPCon Poland 2016)
The road to continuous deployment (PHPCon Poland 2016)Michiel Rook
 
The road to continuous deployment (DomCode September 2016)
The road to continuous deployment (DomCode September 2016)The road to continuous deployment (DomCode September 2016)
The road to continuous deployment (DomCode September 2016)Michiel Rook
 
CQRS & event sourcing in the wild
CQRS & event sourcing in the wildCQRS & event sourcing in the wild
CQRS & event sourcing in the wildMichiel Rook
 
The road to continuous deployment: a case study (DPC16)
The road to continuous deployment: a case study (DPC16)The road to continuous deployment: a case study (DPC16)
The road to continuous deployment: a case study (DPC16)Michiel Rook
 
Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)Michiel Rook
 

More from Michiel Rook (6)

CQRS & Event Sourcing in the wild (ScotlandPHP 2016)
CQRS & Event Sourcing in the wild (ScotlandPHP 2016)CQRS & Event Sourcing in the wild (ScotlandPHP 2016)
CQRS & Event Sourcing in the wild (ScotlandPHP 2016)
 
The road to continuous deployment (PHPCon Poland 2016)
The road to continuous deployment (PHPCon Poland 2016)The road to continuous deployment (PHPCon Poland 2016)
The road to continuous deployment (PHPCon Poland 2016)
 
The road to continuous deployment (DomCode September 2016)
The road to continuous deployment (DomCode September 2016)The road to continuous deployment (DomCode September 2016)
The road to continuous deployment (DomCode September 2016)
 
CQRS & event sourcing in the wild
CQRS & event sourcing in the wildCQRS & event sourcing in the wild
CQRS & event sourcing in the wild
 
The road to continuous deployment: a case study (DPC16)
The road to continuous deployment: a case study (DPC16)The road to continuous deployment: a case study (DPC16)
The road to continuous deployment: a case study (DPC16)
 
Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)Phing - A PHP Build Tool (An Introduction)
Phing - A PHP Build Tool (An Introduction)
 

Recently uploaded

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
[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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Building and deploying PHP applications with Phing

  • 1. Building and deploying PHP applications with Phing Michiel Rook PHP UK Conference 2012
  • 2. About me • Freelance PHP & Java contractor / consultant • PHP since ’99 • Phing project lead • http://www.linkedin.com/in/michieltcs • @michieltcs Building and deploying PHP applications with Phing
  • 3. This Talk • Why use a build tool • What is Phing • Usage • Various examples • Extending Phing Building and deploying PHP applications with Phing
  • 4. Why Use A Build Tool?
  • 5. Why Use A Build Tool Repetition http://www.flickr.com/photos/andrewmalone/5162632817/ Building and deploying PHP applications with Phing
  • 6. Repetition • We are human • We get bored • We forget things • We make mistakes Building and deploying PHP applications with Phing
  • 7. Repetition • Version control • (Unit) Testing • Configuring • Packaging • Uploading • DB changes • ... Building and deploying PHP applications with Phing
  • 8. Repetition • Version control • (Unit) Testing • Configuring • Packaging • Uploading • DB changes • ... • Boring! Building and deploying PHP applications with Phing
  • 9. Why Use A Build Tool Automate! http://www.flickr.com/photos/patrick_h/6209981673/ Building and deploying PHP applications with Phing
  • 10. Automate! • Developers, testers, administrators... • Easier handover to new team members • Improves quality • Reduces errors • Saves time • Consolidate scripts, reduce technical debt Building and deploying PHP applications with Phing
  • 11. What Is Phing http://www.flickr.com/photos/canucksfan604/5471322484/ Building and deploying PHP applications with Phing
  • 12. What Is Phing • PHing Is Not GNU make; it’s a PHP project build system or build tool based on Apache Ant. • Originally developed by Binarycloud • Ported to PHP5 by Hans Lellelid • 2004: my first commit • 2009: lead Building and deploying PHP applications with Phing
  • 13. What Can Phing Do • Scripting using XML build files • Human readable • Mostly cross-platform • Minimal dependencies • Interface to various popular (PHP) tools Building and deploying PHP applications with Phing
  • 14. What Can Phing Do • Scripting using XML build files • Human readable • Mostly cross-platform • Minimal dependencies • Interface to various popular (PHP) tools • ”Good glue” Building and deploying PHP applications with Phing
  • 15. What Can Phing Do Building and deploying PHP applications with Phing
  • 16. Why Use Phing • Ant? • Rich set of tasks • Integration with PHP specific tools • Allows you to stay in the PHP infrastructure • Easy to extend • Embed PHP code directly in the build file Building and deploying PHP applications with Phing
  • 18. Installing Phing • PEAR installation $ pear channel-discover pear.phing.info $ pear install [--alldeps] phing/phing • Optionally, install the documentation package $ pear install phing/phingdocs Building and deploying PHP applications with Phing
  • 19. Build Files • Phing uses XML build files • Contain standard elements • Task: code that performs a specific function (svn checkout, mkdir, etc.) • Target: groups of tasks, can optionally depend on other targets • Project: root node, contains multiple targets Building and deploying PHP applications with Phing
  • 20. Example Build File <project name="Example" default="world"> <target name="hello"> <echo>Hello</echo> </target> <target name="world" depends="hello"> <echo>World!</echo> </target> </project> Buildfile: /home/michiel/phing/simple.xml Example > hello: [echo] Hello Example > world: [echo] World! BUILD FINISHED Building and deploying PHP applications with Phing
  • 21. Properties • Simple key-value files (.ini) ## build.properties version=1.0 • Can be expanded by using ${key} in the build file $ phing -propertyfile build.properties ... <project name="Example" default="default"> <target name="default"> <property file="build.properties" /> <echo>${version}</echo> </target> </project> Building and deploying PHP applications with Phing
  • 22. Filesets • Constructs a group of files to process • Supported by most tasks <fileset dir="./application" includes="**"/> <fileset dir="./application"> <include name="**/*.php" /> <exclude name="**/*Test.php" /> </fileset> • References: define once, use many <fileset dir="./application" includes="**" id="files"/> <fileset refid="files"/> Building and deploying PHP applications with Phing
  • 23. Filesets • Selectors allow fine-grained matching on certain attributes • contains, date, file name & size, ... <fileset dir="${dist}"> <and> <filename name="**"/> <date datetime="01/01/2011" when="before"/> </and> </fileset> Building and deploying PHP applications with Phing
  • 24. Mappers & Filters • Transform files during copy/move/... • Mappers • Change filename • Flatten directories • Filters • Strip comments, white space • Replace values • Perform XSLT transformation • Translation (i18n) Building and deploying PHP applications with Phing
  • 25. Mappers & Filters <copy todir="${build}"> <fileset refid="files"/> <mapper type="glob" from="*.txt" to="*.new.txt"/> <filterchain> <replaceregexp> <regexp pattern="rn" replace="n"/> <expandproperties/> </replaceregexp> </filterchain> </copy> Building and deploying PHP applications with Phing
  • 27. Examples • Version control • Unit testing • Packaging • Deployment • Database migration • Continuous integration Building and deploying PHP applications with Phing
  • 28. Version Control • (CVS), SVN, Git <svncopy username="michiel" password="test" repositoryurl="svn://localhost/phing/trunk/" todir="svn://localhost/phing/tags/1.0"/> <svnexport repositoryurl="svn://localhost/project/trunk/" todir="/home/michiel/dev"/> <svnlastrevision repositoryurl="svn://localhost/project/trunk/" propertyname="lastrev"/> <echo>Last revision: ${lastrev}</echo> Building and deploying PHP applications with Phing
  • 29. PHPUnit • Built-in support for most configuration options • Gathers code coverage information • Various output formats (JUnit / Clover) • Reporting (JUnit style) Building and deploying PHP applications with Phing
  • 30. PHPUnit Example • Stop the build when a test fails <phpunit haltonfailure="true" haltonerror="true" bootstrap="my_bootstrap.php" printsummary="true"> <batchtest> <fileset dir="src"> <include name="**/*Test.php"/> </fileset> </batchtest> </phpunit> Buildfile: /home/michiel/phpunit/build.xml Demo > test: [phpunit] Total tests run: 1, Failures: 1, Errors: 0, Incomplete: 0, Skipped: 0, Time elapsed: 0.00591 s Execution of target "test" failed for the following reason: /home/michiel/phpunit/build.xml:3:44: Test FAILURE (testSayHello in class HelloWorldTest): Failed asserting that two strings are equal. Building and deploying PHP applications with Phing
  • 31. PHPUnit Example • Determine which files to include in the coverage report <coverage-setup database="reports/coverage.db"> <fileset dir="src"> <include name="**/*.php"/> <exclude name="**/*Test.php"/> </fileset> </coverage-setup> • Gather code coverage and other data during the test run <phpunit codecoverage="true"> <formatter type="xml" todir="reports"/> <batchtest> <fileset dir="src"> <include name="**/*Test.php"/> </fileset> </batchtest> </phpunit> Building and deploying PHP applications with Phing
  • 32. PHPUnit Example • Generate some reports <phpunitreport infile="reports/testsuites.xml" format="frames" todir="reports/tests"/> <coverage-report outfile="reports/coverage.xml"> <report todir="reports/coverage" title="Demo"/> </coverage-report> Building and deploying PHP applications with Phing
  • 33. Documentation • Phing currently integrates with popular documentation tools • DocBlox • PhpDocumentor • ApiGen • Also supports r(e)ST (reStructuredText) <docblox title="Phing API Documentation" output="docs" quiet="true"> <fileset dir="../../classes"> <include name="**/*.php"/> </fileset> </docblox> Building and deploying PHP applications with Phing
  • 34. DocBlox Building and deploying PHP applications with Phing
  • 35. Packaging • Create bundles or packages • Phing supports most popular formats: tar (pear), zip, phar <pearpkg name="demo" dir="."> <fileset refid="files"/> <option name="outputdirectory" value="./build"/> <option name="description">Test package</option> <option name="version" value="0.1.0"/> <option name="state" value="beta"/> <mapping name="maintainers"> <element> <element key="handle" value="test"/> <element key="name" value="Test"/> <element key="email" value="test@test.nl"/> <element key="role" value="lead"/> </element> </mapping> </pearpkg> Building and deploying PHP applications with Phing
  • 36. Packaging - TAR / ZIP <tar compression="gzip" destFile="package.tgz" basedir="build"/> <zip destfile="htmlfiles.zip"> <fileset dir="."> <include name="**/*.html"/> </fileset> </zip> Building and deploying PHP applications with Phing
  • 37. Packaging - PHAR <pharpackage compression="gzip" destfile="test.phar" stub="stub.php" basedir="."> <fileset dir="hello"> <include name="**/**" /> </fileset> <metadata> <element name="version" value="1.0" /> <element name="authors"> <element name="John Doe"> <element name="e-mail" value="john@example.com" /> </element> </element> </metadata> </pharpackage> Building and deploying PHP applications with Phing
  • 38. Putting it all together - deployments
  • 39. Copying to a server • SSH <scp username="john" password="smith" host="webserver" todir="/www/htdocs/project/"> <fileset dir="test"> <include name="*.html"/> </fileset> </scp> • FTP <ftpdeploy host="server01" username="john" password="smit" dir="/var/www"> <fileset dir="."> <include name="*.html"/> </fileset> </ftpdeploy> Building and deploying PHP applications with Phing
  • 40. Symbolic links • All releases stored in ”backup” directory • Symlink application directory to latest release (similar to Capistrano) • Allows for easy (code) rollbacks <svnlastrevision repositoryurl="${deploy.svn}" property="deploy.rev"/> <svnexport repositoryurl="${deploy.svn}" todir="/www/releases/build-${deploy.rev}"/> <symlink target="/www/releases/build-${deploy.rev}" link="/www/current"/> • Also on a remote server <ssh host="webserver" command="ln -s /www/releases/build-${deploy.rev} /www/current"/> Building and deploying PHP applications with Phing
  • 41. Multiple servers / targets • Several deployment targets: testing, staging, production, ... • Keep one property file per target • Select property file based on input <input propertyname="env" validargs="testing,staging,production"> Enter environment name </input> <property file="${env}.properties"/> <ssh host="${deploy.host}" command="..."/> Building and deploying PHP applications with Phing
  • 42. Database Migration • Set of delta SQL files (1-create-post.sql) • Tracks current version of your db in changelog table • Generates do and undo SQL files CREATE TABLE changelog ( change_number BIGINT NOT NULL, delta_set VARCHAR(10) NOT NULL, start_dt TIMESTAMP NOT NULL, complete_dt TIMESTAMP NULL, applied_by VARCHAR(100) NOT NULL, description VARCHAR(500) NOT NULL ) Building and deploying PHP applications with Phing
  • 43. Database Migration • Delta scripts with do (up) & undo (down) parts --// CREATE TABLE ‘post‘ ( ‘title‘ VARCHAR(255), ‘time_created‘ DATETIME, ‘content‘ MEDIUMTEXT ); --//@UNDO DROP TABLE ‘post‘; --// Building and deploying PHP applications with Phing
  • 44. Database Migration <dbdeploy url="sqlite:test.db" dir="deltas" outputfile="deploy.sql" undooutputfile="undo.sql"/> <pdosqlexec src="deploy.sql" url="sqlite:test.db"/> Buildfile: /home/michiel/dbdeploy/build.xml Demo > migrate: [dbdeploy] Getting applied changed numbers from DB: mysql:host=localhost;dbname=demo [dbdeploy] Current db revision: 0 [dbdeploy] Checkall: [pdosqlexec] Executing file: /home/michiel/dbdeploy/deploy.sql [pdosqlexec] 3 of 3 SQL statements executed successfully BUILD FINISHED Building and deploying PHP applications with Phing
  • 45. Database Migration -- Fragment begins: 1 -- INSERT INTO changelog (change_number, delta_set, start_dt, applied_by, description) VALUES (1, ’Main’, NOW(), ’dbdeploy’, ’1-create_initial_schema.sql’); --// CREATE TABLE ‘post‘ ( ‘title‘ VARCHAR(255), ‘time_created‘ DATETIME, ‘content‘ MEDIUMTEXT ); UPDATE changelog SET complete_dt = NOW() WHERE change_number = 1 AND delta_set = ’Main’; -- Fragment ends: 1 -- Building and deploying PHP applications with Phing
  • 46. Database Migration -- Fragment begins: 1 -- DROP TABLE ‘post‘; --// DELETE FROM changelog WHERE change_number = 1 AND delta_set = ’Main’; -- Fragment ends: 1 -- Building and deploying PHP applications with Phing
  • 47. Phing & Jenkins • Continuous integration • Phing plugin • Build periodically or after each commit • Verify and test the build • Deploy results Building and deploying PHP applications with Phing
  • 48. Phing & Jenkins Building and deploying PHP applications with Phing
  • 49. Phing & Jenkins Building and deploying PHP applications with Phing
  • 50. Phing & Jenkins Building and deploying PHP applications with Phing
  • 53. Extending Phing • Numerous extension points • Tasks • Types • Selectors • Filters • Mappers • Loggers • ... Building and deploying PHP applications with Phing
  • 54. Sample Task • Extends from Task • Contains main() method and optionally init() • Setter method for each attribute in the build file class SampleTask extends Task { private $var; public function setVar($v) { $this->var = $v; } public function main() { $this->log("value: " . $this->var); } } Building and deploying PHP applications with Phing
  • 55. Sample Task • Use taskdef to make Phing aware of your new task <project name="Example" default="default"> <taskdef name="sample" classpath="/dev/src" classname="tasks.my.SampleTask" /> <target name="default"> <sample var="Hello World" /> </target> </project> Building and deploying PHP applications with Phing
  • 56. Ad Hoc Extension • Define a task within your build file <target name="main"> <adhoc-task name="foo"><![CDATA[ class FooTest extends Task { private $bar; function setBar($bar) { $this->bar = $bar; } function main() { $this->log("In FooTest: " . $this->bar); } } ]]></adhoc-task> <foo bar="TEST"/> </target> Building and deploying PHP applications with Phing
  • 57. Future Improvements • More tasks & support • Better performance • PHAR package (including popular dependencies) • More documentation • Increased test coverage • IDE support Building and deploying PHP applications with Phing
  • 58. Future Improvements • More tasks & support • Better performance • PHAR package (including popular dependencies) • More documentation • Increased test coverage • IDE support • Pull requests! :-) Building and deploying PHP applications with Phing
  • 59. Helpful Links • http://pear.php.net/ • http://www.docblox-project.org/ • http://www.dbdeploy.com/ • http://www.jenkins-ci.org/ • http://www.phing.info/docs/guide/stable/ • http://github.com/phingofficial/phing Building and deploying PHP applications with Phing
  • 60. Questions? http://joind.in/4954 http://www.phing.info #phing (freenode) @phingofficial Thank you! Building and deploying PHP applications with Phing