The document discusses building testable PHP applications. It covers topics like testing code, testable architecture, dependency injection, and static code analysis tools like PHP Code Sniffer, PHP Mess Detector, and PHP Copy Paster Detector. The document emphasizes that writing tests and designing for testability leads to fewer bugs and more maintainable code. It provides examples of unit testing and recommends test-driven development practices.
This document provides examples of unit testing code in PHP using PHPUnit. It demonstrates how to write test cases with assertions, use PHPUnit features like data providers and expected exceptions, and addresses challenges like external dependencies by implementing dependency injection. Mocking and stubs are also presented as ways to isolate code during testing. The overall content aims to explain PHPUnit and best practices for writing clean, isolated and effective unit tests.
The document discusses how to write unit tests for PHP code using the PHPUnit testing framework. It provides an example of testing a Math class that contains a sum() method. It demonstrates creating a test case class called MathTest that extends PHPUnit's test case class. The MathTest class contains a testSum() method that asserts the expected output of calls to Math::sum() using PHPUnit's assertion methods. It also shows how to use a data provider method to pass multiple sets of parameters to the test method.
This document discusses PHPUnit, a unit testing framework for PHP. It covers PHPUnit installation, writing test cases, assertions, fixtures, organizing tests, and best practices for test naming, structure and design including the F.I.R.S.T. principles. Key topics include using PHPUnit to test classes, methods and exceptions, leveraging data providers, fixtures for shared test setup/teardown, and keeping tests clean with single concepts per test.
This document discusses mocking dependencies in PHPUnit tests. It begins by defining dependencies and dependency injection, and why it is important to mock dependencies in unit tests. It then covers defining test doubles like mocks, stubs, and dummies to simulate dependencies. Various examples are provided for mocking different types of dependencies, like APIs, databases, and external data sources. The goal of mocking is to test units of code in isolation without relying on other components, in order to make tests faster and more reliable.
A lot of people using PHPunit for testing their source code. While I was observing my team I recognized most of them are only using the standard assertions like 'assertEquals()' and are complaining about how hard it is to test the code even when the tests are written first. This talk is about all the stuff not used on a daily basis and it digs deep into uncommon features of PHPUnit.
The document discusses various techniques for testing code such as stubs, mocks, and fakes. It explains that stubs provide canned answers to function calls during a test. Mocks verify that functions are called correctly. Fakes have working implementations but take shortcuts. The document also discusses challenges in testing like dependencies and non-deterministic objects. It advocates for techniques like dependency injection and inversion of control to make code more testable and avoid direct dependencies.
phpunit is testing framework for php testing.
A browser is able to give the syntax error but what if in case of some logical error.
Phpunit testing enables you to check your logic.
It is fully object oriented framework.
It also can be enabled in Netbeans.
you can find the option of phpunit testing in Netbeans
Here are a few key points about using PHPUnit for Selenium testing:
- PHPUnit provides a SeleniumTestCase class that allows you to write Selenium tests that extend it. This gives you access to Selenium commands like open(), type(), click(), assertTitle(), etc.
- You'll need to have Selenium Server and a supported browser (Firefox, Chrome, IE) installed to run the tests.
- Tests using SeleniumTestCase are more like integration/acceptance tests that simulate user interactions and verify page content rather than isolated unit tests.
- Common things to test include page titles, form submissions, link navigation, page content validation after actions.
- Selenium IDE can be used to record tests that can be exported to PHPUnit
Unit testing, everyone talks about it and wants to do it but never gets around to actually start testing. Complex spaghetti code and time / budget pressures are often the reasons why nobody dives in and gets started with testing. But when the application breaks, and people loose money or worse it's often too late.
In this talk I will take you on a journey with real examples that will show you how you can set up your tests, how to test complex situations with legacy spaghetti code, test web services, database interactions and how to gradually build a solid foundation to safeguard the core code base and everything around it.
Don't you want to be confident when you walk out the office?
Everyone talks about raising the bar on quality of code, but it's always hard to start implementing it when you have no clue where to start. With this talk I'm shooing that there are many levels developers can improve themselves by using the right tools. In this talk I'll go over each tool with examples how to use them against your codebase. A must attend talk for every developer that wants to scale up their quality. Most PHP developers deploy code that does what the customer requested but they don't have a clue about the quality of the product they deliver. Without this knowledge, maintenance can be a hell and very expensive. In this workshop I cover unit testing, code measuring, performance testing, debugging and profiling and give tips and tricks how to continue after this workshop.
Nothing is as frustrated as deploying a new release of your web application to find out functionality you had doesn't work anymore. Of course you have all your unit tests in place and you run them through your CI environment, but nothing prepared you to a failing javascript error or a link that doesn't work anymore. Welcome to User Acceptance testing or UAT. Before you start putting real people in front of your application, create macros and export them as PHPUnit test classes. Then run them in an automated way just like your unit tests and hook them into your CI. In this talk I will show you how easy it is to create Selenium macros that can be converted into PHPUnit scripts and run automatically on different virtual machines (VM's) so you can test all different browsers on a diversity of operating systems.
This document provides best practices for writing PHPUnit tests, including: do not write tests that do not test anything or test too much; exploit dependencies between tests; use the most specific assertion; decouple test code from test data; organize tests by class; run tests via XML configuration; disable unnecessary PHPUnit features; use code coverage whitelisting; annotate tests to make coverage more meaningful; and avoid unnecessary patterns like singletons.
- The document discusses best practices for writing PHPUnit tests, including writing tests, upgrading to PHPUnit 3.7, installing PHPUnit via different methods like PHAR, Composer, and PEAR, using specific assertions, and having a fast test suite.
- It recommends separating tests by folder structure or config file, only testing relevant behaviors of classes rather than internal methods, and not testing simple getters and setters. The goal is writing clean, testable code and tests that verify class behaviors rather than implementation details.
This document provides an overview of unit testing in PHP using PHPUnit. It discusses some goals of test automation like improving quality and reducing risks. It also covers the testing continuum from unit to integration to functional tests. The document introduces PHPUnit and how it is based on the xUnit family of tools. It then walks through an example of writing the first PHPUnit test to test a ROT13 encoding function in a test-driven way, demonstrating best practices like following the RED-GREEN-REFACTOR process and using assertions. Finally, it discusses principles of good test automation like independence of tests and isolating the system under test.
This workshop is a hands-on training where a real Zend Framework application is used as an example to start improving QA using tools to test, document and perform software metric calculations to indicate where the software can be improved. I also explain the reports produced by a CI system.
PHPUnit is an automated unit testing framework for PHP. It allows developers to write tests for their code in PHP and run those tests to determine if the code is working as expected. Some key aspects of PHPUnit include writing tests in classes that extend the PHPUnit test case class, using assertions to validate expected outcomes, and the ability to test databases and output using PHPUnit extensions. PHPUnit is widely used for test-driven development in PHP projects.
The document discusses testing code and assuring quality by learning to use the Perl modules Test::More, Perl::Critic, and Devel::Cover. It provides an overview of different testing techniques in Perl including writing unit tests, ensuring code quality and test coverage, and using the prove command-line tool to run tests.
This document provides an overview of quality assurance for PHP projects. It discusses the importance of revision control, documentation, testing, and automation in QA. Revision control systems like SVN and Git are recommended for team development and tracking code versions. PHP Lint is introduced for syntax checking files from the command line. Documenting code with PHPDoc is suggested. Unit testing forms and models is demonstrated using PHPUnit. Validation, filtering, and sanitizing user input is important for protection against exploits. Overall the document promotes establishing strong quality practices like testing, revision control, and documentation for PHP projects.
Test your code like a pro - PHPUnit in practiceSebastian Marek
?
The day you realised that you can¨t really tell what your code does is the day you stop being an amateur programmer and you turn into a professional developer. During this workshop you will learn about the most famous unit testing framework C PHPUnit, how it can help you gain confidence in your code and what to do (and what to avoid) to make your code testable. We will discuss unit testing best practices and talk about tools that can help you automate the whole process, so it becomes more of a habit then a necessity.
This document introduces unit testing with PHPUnit. It discusses what unit testing is, why it's important, and tools like SimpleTest and PHPUnit. It provides examples of basic unit tests for a HelloWorld class using PHPUnit. It also covers more advanced testing techniques like data providers, expected exceptions, fixtures, doubles, mocks, stubs, and database testing using examples like testing a BankAccount class. The document provides hints and tips for unit testing MVC frameworks like Zend Framework.
This document provides an overview of PHPUnit, a unit testing framework for PHP. It introduces Sebastian Bergmann, the creator of PHPUnit, and describes some of PHPUnit's key features like test frameworks, integration with other tools, code coverage, and more. Examples are provided of writing unit tests with PHPUnit using the PHPUnit_Framework_TestCase class. Additional features like annotations, data providers, exceptions, groups, and behavior-driven development styles are also demonstrated.
Unit testing with PHPUnit - there's life outside of TDDPawe? Michalik
?
Basics of PHPUnit and why is it even more relevant in legacy code. Key points of the framework are explained, along with mocking objects, test organisation, creating documentations with tests and accessing non-public objects (where applicable).
Live version with additional notes available at: http://pawelmichalik.net/presentations/unit-testing-with-phpunit?showNotes=true
Prezentacja dost?pna tak?e w j?zyku polskim: http://pawelmichalik.net/prezentacje/testy-jednostkowe-w-phpunit?showNotes=true
This document provides an introduction and overview of unit testing in PHP. It discusses what unit testing is, the benefits of unit testing, and some key aspects of unit testing like test isolation, automation, and speed. It also introduces the PHPUnit testing framework as the de facto standard for PHP unit testing. Examples are provided of unit testing a multiplication function with PHPUnit by creating test cases to assert expected outcomes. The document also discusses differences between unit testing and integration testing and refactoring code to be more testable through techniques like dependency injection.
The document discusses unit testing and the PHPUnit testing framework. It provides an overview of what unit testing is, why it is useful, and how to get started with PHPUnit. Key points include that unit testing finds bugs early, encourages good coding practices, and makes codebases easier to change and deploy. PHPUnit is introduced as the most popular PHP testing framework. Instructions are given for installing PHPUnit via PEAR and writing basic tests, including test fixtures, assertions, and annotations. More advanced topics like mock objects, data providers, and exception testing are also covered.
This document provides an overview of test driven development with PHPUnit. It discusses what unit testing is, the benefits of testing, and how to get started with PHPUnit. Key topics covered include writing tests, assertions, dependencies, data providers, testing errors and exceptions, fixtures, and database testing. The document also mentions test output, incomplete/skipped tests, test doubles, code coverage analysis, and the skeleton generator.
Diving into HHVM Extensions (PHPNW Conference 2015)James Titcumb
?
HHVM is currently gaining popularity at quite a pace, and it's a pretty exciting time for PHP runtimes. Have you ever wondered what is going on beneath this slick and super-speedy engine? I wondered that myself, so I dived into the internals of HHVM, discovering a treasure trove of awesome stuff. In this talk, I'll show you how HHVM itself works with a guided tour of the codebase, demonstrating how it all pieces together. I'll also show you a couple of ways to write your own incredible HHVM extension. You don't need to know C++ to understand this talk - just PHP language knowledge is enough.
The document discusses unit testing in Laravel. It provides an overview of why unit testing is important, how to set up and configure unit tests in Laravel using PHPUnit, and examples of writing different types of tests including HTTP requests, file uploads, database queries, and browser tests using Dusk. Key points covered include the benefits of testing, how to generate and structure test files, common assertions to make in tests, and tips for test-driven development.
This document discusses Wade Arnold's experience with PHP and Zend Framework. It provides an overview of Wade's background working on Zend Amf and other PHP projects. It also includes examples of file structures, models, and services that demonstrate how to build a PHP application that integrates with Flash using Zend Amf. The document advocates for using standards like Zend Framework to build robust PHP applications and services.
This document introduces PHPSpec, a BDD framework for PHP inspired by RSpec. It discusses the principles of behavior-driven development (BDD) and test-driven development (TDD), and how PHPSpec implements a domain-specific language (DSL) that allows developers to write specifications in a natural language style. The document provides examples of how to write PHPSpec specifications using its matchers and contexts, run the specifications, and handle pending and failing tests. It also briefly discusses related tools like mocks, screen scraping with Goutte, and how BDD fits into the development cycle.
Unit testing, everyone talks about it and wants to do it but never gets around to actually start testing. Complex spaghetti code and time / budget pressures are often the reasons why nobody dives in and gets started with testing. But when the application breaks, and people loose money or worse it's often too late.
In this talk I will take you on a journey with real examples that will show you how you can set up your tests, how to test complex situations with legacy spaghetti code, test web services, database interactions and how to gradually build a solid foundation to safeguard the core code base and everything around it.
Don't you want to be confident when you walk out the office?
Everyone talks about raising the bar on quality of code, but it's always hard to start implementing it when you have no clue where to start. With this talk I'm shooing that there are many levels developers can improve themselves by using the right tools. In this talk I'll go over each tool with examples how to use them against your codebase. A must attend talk for every developer that wants to scale up their quality. Most PHP developers deploy code that does what the customer requested but they don't have a clue about the quality of the product they deliver. Without this knowledge, maintenance can be a hell and very expensive. In this workshop I cover unit testing, code measuring, performance testing, debugging and profiling and give tips and tricks how to continue after this workshop.
Nothing is as frustrated as deploying a new release of your web application to find out functionality you had doesn't work anymore. Of course you have all your unit tests in place and you run them through your CI environment, but nothing prepared you to a failing javascript error or a link that doesn't work anymore. Welcome to User Acceptance testing or UAT. Before you start putting real people in front of your application, create macros and export them as PHPUnit test classes. Then run them in an automated way just like your unit tests and hook them into your CI. In this talk I will show you how easy it is to create Selenium macros that can be converted into PHPUnit scripts and run automatically on different virtual machines (VM's) so you can test all different browsers on a diversity of operating systems.
This document provides best practices for writing PHPUnit tests, including: do not write tests that do not test anything or test too much; exploit dependencies between tests; use the most specific assertion; decouple test code from test data; organize tests by class; run tests via XML configuration; disable unnecessary PHPUnit features; use code coverage whitelisting; annotate tests to make coverage more meaningful; and avoid unnecessary patterns like singletons.
- The document discusses best practices for writing PHPUnit tests, including writing tests, upgrading to PHPUnit 3.7, installing PHPUnit via different methods like PHAR, Composer, and PEAR, using specific assertions, and having a fast test suite.
- It recommends separating tests by folder structure or config file, only testing relevant behaviors of classes rather than internal methods, and not testing simple getters and setters. The goal is writing clean, testable code and tests that verify class behaviors rather than implementation details.
This document provides an overview of unit testing in PHP using PHPUnit. It discusses some goals of test automation like improving quality and reducing risks. It also covers the testing continuum from unit to integration to functional tests. The document introduces PHPUnit and how it is based on the xUnit family of tools. It then walks through an example of writing the first PHPUnit test to test a ROT13 encoding function in a test-driven way, demonstrating best practices like following the RED-GREEN-REFACTOR process and using assertions. Finally, it discusses principles of good test automation like independence of tests and isolating the system under test.
This workshop is a hands-on training where a real Zend Framework application is used as an example to start improving QA using tools to test, document and perform software metric calculations to indicate where the software can be improved. I also explain the reports produced by a CI system.
PHPUnit is an automated unit testing framework for PHP. It allows developers to write tests for their code in PHP and run those tests to determine if the code is working as expected. Some key aspects of PHPUnit include writing tests in classes that extend the PHPUnit test case class, using assertions to validate expected outcomes, and the ability to test databases and output using PHPUnit extensions. PHPUnit is widely used for test-driven development in PHP projects.
The document discusses testing code and assuring quality by learning to use the Perl modules Test::More, Perl::Critic, and Devel::Cover. It provides an overview of different testing techniques in Perl including writing unit tests, ensuring code quality and test coverage, and using the prove command-line tool to run tests.
This document provides an overview of quality assurance for PHP projects. It discusses the importance of revision control, documentation, testing, and automation in QA. Revision control systems like SVN and Git are recommended for team development and tracking code versions. PHP Lint is introduced for syntax checking files from the command line. Documenting code with PHPDoc is suggested. Unit testing forms and models is demonstrated using PHPUnit. Validation, filtering, and sanitizing user input is important for protection against exploits. Overall the document promotes establishing strong quality practices like testing, revision control, and documentation for PHP projects.
Test your code like a pro - PHPUnit in practiceSebastian Marek
?
The day you realised that you can¨t really tell what your code does is the day you stop being an amateur programmer and you turn into a professional developer. During this workshop you will learn about the most famous unit testing framework C PHPUnit, how it can help you gain confidence in your code and what to do (and what to avoid) to make your code testable. We will discuss unit testing best practices and talk about tools that can help you automate the whole process, so it becomes more of a habit then a necessity.
This document introduces unit testing with PHPUnit. It discusses what unit testing is, why it's important, and tools like SimpleTest and PHPUnit. It provides examples of basic unit tests for a HelloWorld class using PHPUnit. It also covers more advanced testing techniques like data providers, expected exceptions, fixtures, doubles, mocks, stubs, and database testing using examples like testing a BankAccount class. The document provides hints and tips for unit testing MVC frameworks like Zend Framework.
This document provides an overview of PHPUnit, a unit testing framework for PHP. It introduces Sebastian Bergmann, the creator of PHPUnit, and describes some of PHPUnit's key features like test frameworks, integration with other tools, code coverage, and more. Examples are provided of writing unit tests with PHPUnit using the PHPUnit_Framework_TestCase class. Additional features like annotations, data providers, exceptions, groups, and behavior-driven development styles are also demonstrated.
Unit testing with PHPUnit - there's life outside of TDDPawe? Michalik
?
Basics of PHPUnit and why is it even more relevant in legacy code. Key points of the framework are explained, along with mocking objects, test organisation, creating documentations with tests and accessing non-public objects (where applicable).
Live version with additional notes available at: http://pawelmichalik.net/presentations/unit-testing-with-phpunit?showNotes=true
Prezentacja dost?pna tak?e w j?zyku polskim: http://pawelmichalik.net/prezentacje/testy-jednostkowe-w-phpunit?showNotes=true
This document provides an introduction and overview of unit testing in PHP. It discusses what unit testing is, the benefits of unit testing, and some key aspects of unit testing like test isolation, automation, and speed. It also introduces the PHPUnit testing framework as the de facto standard for PHP unit testing. Examples are provided of unit testing a multiplication function with PHPUnit by creating test cases to assert expected outcomes. The document also discusses differences between unit testing and integration testing and refactoring code to be more testable through techniques like dependency injection.
The document discusses unit testing and the PHPUnit testing framework. It provides an overview of what unit testing is, why it is useful, and how to get started with PHPUnit. Key points include that unit testing finds bugs early, encourages good coding practices, and makes codebases easier to change and deploy. PHPUnit is introduced as the most popular PHP testing framework. Instructions are given for installing PHPUnit via PEAR and writing basic tests, including test fixtures, assertions, and annotations. More advanced topics like mock objects, data providers, and exception testing are also covered.
This document provides an overview of test driven development with PHPUnit. It discusses what unit testing is, the benefits of testing, and how to get started with PHPUnit. Key topics covered include writing tests, assertions, dependencies, data providers, testing errors and exceptions, fixtures, and database testing. The document also mentions test output, incomplete/skipped tests, test doubles, code coverage analysis, and the skeleton generator.
Diving into HHVM Extensions (PHPNW Conference 2015)James Titcumb
?
HHVM is currently gaining popularity at quite a pace, and it's a pretty exciting time for PHP runtimes. Have you ever wondered what is going on beneath this slick and super-speedy engine? I wondered that myself, so I dived into the internals of HHVM, discovering a treasure trove of awesome stuff. In this talk, I'll show you how HHVM itself works with a guided tour of the codebase, demonstrating how it all pieces together. I'll also show you a couple of ways to write your own incredible HHVM extension. You don't need to know C++ to understand this talk - just PHP language knowledge is enough.
The document discusses unit testing in Laravel. It provides an overview of why unit testing is important, how to set up and configure unit tests in Laravel using PHPUnit, and examples of writing different types of tests including HTTP requests, file uploads, database queries, and browser tests using Dusk. Key points covered include the benefits of testing, how to generate and structure test files, common assertions to make in tests, and tips for test-driven development.
This document discusses Wade Arnold's experience with PHP and Zend Framework. It provides an overview of Wade's background working on Zend Amf and other PHP projects. It also includes examples of file structures, models, and services that demonstrate how to build a PHP application that integrates with Flash using Zend Amf. The document advocates for using standards like Zend Framework to build robust PHP applications and services.
This document introduces PHPSpec, a BDD framework for PHP inspired by RSpec. It discusses the principles of behavior-driven development (BDD) and test-driven development (TDD), and how PHPSpec implements a domain-specific language (DSL) that allows developers to write specifications in a natural language style. The document provides examples of how to write PHPSpec specifications using its matchers and contexts, run the specifications, and handle pending and failing tests. It also briefly discusses related tools like mocks, screen scraping with Goutte, and how BDD fits into the development cycle.
This document contains sample questions for the Zend Certification PHP 5 exam. It includes multiple choice questions testing PHP 5 language features and best practices related to topics like XML processing, database access, regular expressions, and security. The questions cover syntax, functions, patterns and other PHP concepts that could appear on the certification exam.
CakePHP 2.0 has been re-factored and rebuilt with many internal and external API changes. It uses native PHP5 features, updated conventions for class and file names, and a new loader. Exceptions replace the old error handling. Collections unify how helpers, components, behaviors and tasks are loaded and used. The console, request/response, sessions, authentication, email, and testing have all been improved for better performance and extensibility. Benchmarks show CakePHP 2.0 has significantly better performance than 1.3.11.
This document summarizes some new features in PHP 5.4:
- Array syntax can now be written more concisely using square brackets instead of array functions.
- PHP 5.4 includes a built-in web server for development purposes, allowing PHP scripts to be run without Apache.
- Traits allow sharing of methods across classes to reduce code duplication, similar to mixins in Ruby.
- Closures now support accessing properties of the enclosing class scope via $this.
The document discusses several software design patterns and concepts used in Zend Framework 3 including singleton, dependency injection, factory, data mapper, caching, and logging. It provides definitions and examples of how each pattern addresses issues like high cohesion, loose coupling, and testability. Key benefits are outlined such as reusability, reduced dependencies, and more readable code.
This document discusses strategies for modernizing legacy code through an iterative process. It recommends starting by breaking dependencies with minimal changes while applying tests. Small changes should then be made and tests cleaned up before refactoring code to a cleaner state. The document outlines approaches like partial mocking, dependency injection, and out-of-context testing to break dependencies in an untestable code. It stresses adding tests incrementally and refactoring both production code and tests as the process continues.
This document discusses PHPSpec, a behavior-driven development (BDD) framework for PHP. It begins by explaining what PHPSpec is and how it implements BDD through a domain-specific language (DSL) based on RSpec. The document then covers how PHPSpec specifies tests using contexts, examples, expectations, matchers, mocks, and stubs. It provides examples of writing PHPSpec tests and using various PHPSpec features. The document concludes by mentioning upcoming PHPSpec features and linking to resources for learning more.
Can't Miss Features of PHP 5.3 and 5.4Jeff Carouth
?
If you're like me you remember the days of PHP3 and PHP4; you remember when PHP5 was released, and how it was touted to change to your life. It's still changing and there are some features of PHP 5.3 and new ones coming with PHP 5.4 that will improve your code readability and reusability. Let's look at some touted features such as closures, namespaces, and traits, as well as some features being discussed for future releases.
Practical tips for dealing with projects involving legacy code. Covers investigating past projects, static analysis of existing code, and methods for changing legacy code.
Presented at PHP Benelux '10
This document discusses using CakePHP to develop an e-commerce application that integrates with Amazon's APIs. It describes extending CakePHP controllers and models to work with Amazon data, using ClassRegistry to initialize models within models' constructors, and testing with a custom database configuration for the Amazon data source. Key classes and behaviors are extended, and a class registry pattern is implemented to reduce duplication and improve organization.
Review unknown code with static analysis - bredaphpDamien Seguy
?
Code quality is not just for christmas, it is a daily part of the job. So, what do you do when you're handed with a five feet long pole a million lines of code that must be vetted ? You call static analysis to the rescue. During one hour, we'll be reviewing totally unknown code code : no name, no usage, not a clue. We'll apply a wide range of tools, reaching for anything that helps us understand the code and form an opinion on it. Can we break this mystery and learn how everyone else is looking at our code ?
Symfony is a PHP web framework that provides features like templating, caching, internationalization and MVC architecture out of the box. It uses the Model-View-Controller pattern and includes tools for scaffolding, routing, form generation and more. Symfony projects can be created via the command line and include an auto-generated directory structure for applications, modules and actions.
Even nowadays, PHP code is mostly manually audited. Expert pore over actual code, in search for bugs or code smells. Actually, it is possible to have PHP do this work itself ! Strengthened with the internal Tokenizer, bolstered by the manual, it is able to scan thousands of lines of code, without getting bored, and bringing pragmatic pieces of wisdom: official manual recommendations, version migration, code pruning and security. In the end, it deliver a global overview of the code, without reading it.
Creating "Secure" PHP Applications, Part 1, Explicit Code & QAarchwisp
?
The document provides tips for writing more secure PHP code such as using typing assertions and avoiding global variables, recommends using tools like PHPMD and PHPCS to analyze code quality and identify issues, and emphasizes the importance of unit testing, continuous integration, and secure deployment practices.
Learn how to write scripted load tests in PHP to run against your system without breaking the bank. Jason will cover not only the importance of load testing, but share stories of how load tests uncovered problems that would otherwise not have been discovered until production. Also, learn how to use load testing to learn how to deal with large traffic sites without needing to be employed by a large scale site first. We¨ll be using RedLine13, an almost free load testing tool that is at the same time inexpensive, easy, and effective.
Best Practices in Plugin Development (WordCamp Seattle)andrewnacin
?
My talk -- officially named "Y U NO CODE WELL" -- at WordCamp Seattle 2011 on best practices during plugin development. Find the video, as it provides some good context and conversation.
This document discusses using Zend Framework for building web applications. It describes how Zend_Application provides dependency injection and configuration without requiring objects. It also covers using Zend_Db for database access, Zend_Controller for routing, and Zend_Translate for internationalization. Validation is discussed, including using Zend_Validate with Zend_Translate to internationalize error messages.
Innovative Specifications for Better Performance Logging and MonitoringCary Millsap
?
Imagine a car with no speedometer. There are speed limit signs and policemen all around with radar guns waiting to catch you speeding, but you have no way of knowing how fast you're going. Of course, a car like this has no openable hood (no bonnet), so to change the air filter, you have to hire a specialist to saw into the body of your car. A car like this would be preposterous. Yet people write software like this all the time.
The Oracle Database has some of the best performance logging features built into it of any software in the world. You can use it with any application!even applications that were built without logging and monitoring in mind. But you can go SO much further if you bother to include some performance logging features in your application. In this session, I explain Oracle's extended SQL tracing feature and describe how to enable and disable it. Then I show some innovative ideas that will help you design and build database applications that are easier to monitor, manage, and maintain throughout the software development life cycle.
15. public function testSaveUpdatesDatabase()
{
$mapper = new IBLFranchiseMapper($this->_conn);
$franchise = new IBLFranchise();
$franchise->setId(25);
$franchise->setNickname('TST');
$franchise->setName('Test Team');
$franchise->setConference('Conference');
$franchise->setDivision('Division');
$franchise->setIp(0);
$mapper->save($franchise);
// Update existing model
$franchise->setIp(35);
$mapper->save($franchise);
// Reload Franchise record and compare them
$franchise2 = $mapper->findById($franchise->getId());
$this->assertEquals(35, $franchise2->getIp());
// Clean up the franchise
$mapper->delete($franchise);
}
16. My preferred
Behaviour-Driven
Development framework
17. Feature: ls
In order to see the directory structure
As a UNIX user
I need to be able to list the current
directory's contents
Scenario: List 2 files in a directory
Given I am in a directory "test"
And I have a file named "foo"
And I have a file named "bar"
When I run "ls"
Then I should get:
"""
bar
foo
"""
18. Excuses are like
nipples, everyone has
at least one
^Writing tests will slow me down. ̄
^Why can¨t we just manually test in the browser? ̄
^I¨d be done with this already if I didn¨t have to
write the tests! ̄
19. ^A project using TDD would take 20 to 40%
longer to complete but resulted in 40 to 90%
fewer bugs discovered in production. ̄
http://www.infoq.com/news/2009/03/TDD-Improves-Quality
26. PHP Code Sniffer
Enforcement of code to expected standard
Create your own ^code sniffs ̄ if required
Great if team having problems with consistency
27. chartjes@yggdrasil [09:39:37] [~/Sites/local.ibl/lib/ibl] [master *]
-> % phpcs FranchiseMapper.php
FILE: /Users/chartjes/Sites/local.ibl/lib/ibl/FranchiseMapper.php
FOUND 13 ERROR(S) AND 5 WARNING(S) AFFECTING 18 LINE(S)
2 | ERROR | Missing file doc comment
5 | ERROR | Missing class doc comment
6 | ERROR | Expected 0 spaces before opening brace; 1 found
10 | ERROR | You must use "/**" style comments for a function comment
| Missing function doc comment
15 | WARNING | Line exceeds 85 characters; contains 86 characters
20 | ERROR | Missing function doc comment
36 | ERROR | Missing function doc comment
53 | ERROR | Missing function doc comment
74 | ERROR | Missing function doc comment
95 | ERROR | Missing function doc comment
139 | WARNING | Line exceeds 85 characters; contains 90 characters
142 | WARNING | Line exceeds 85 characters; contains 181 characters
149 | ERROR | Missing function doc comment
152 | WARNING | Line exceeds 85 characters; contains 117 characters
154 | WARNING | Line exceeds 85 characters; contains 86 characters
28. PHP Mess Detector
Identi?es code that is complex
Make suggestions on changes
29. > % phpmd lib/vendor/Moontoast/RpcApi.php text
codesize,design,naming,unusedcode
RpcApi.php:12 The class RpcApi has an overall complexity of 77 which
is very high. The configured complexity threshold is 50
high. The configured complexity threshold is 50.
RpcApi.php:12 The class RpcApi has a coupling between objects value
of 14. Consider to reduce to number of dependencies under 13
RpcApi.php:27 Avoid unused parameters such as '$params'.
RpcApi.php:114 The method getProduct() has a Cyclomatic Complexity of 14.
RpcApi.php:114 The method getProduct() has an NPath complexity of 655.
RpcApi.php:114 Avoid really long methods.
RpcApi.php:114 Avoid variables with short names like $id
RpcApi.php:234 Avoid unused parameters such as '$params'.
RpcApi.php:282 The method getStore() has a Cyclomatic Complexity of 12.
RpcApi.php:282 Avoid really long methods.
RpcApi.php:302 Avoid unused local variables such as '$price'.
RpcApi.php:303 Avoid unused local variables such as '$previousPrice'.
RpcApi.php:398 Avoid unused parameters such as '$csc'
RpcApi.php:477 The method saveCart() has a Cyclomatic Complexity of 26
RpcApi.php:477 Avoid really long methods
RpcApi.php:477 Avoid variables with short names like $id
RpcApi.php:477 Avoid excessively long variable names like
$useBillingForShipping
RpcApi.php:588 The method saveCart() has an NPath complexity of 5644802.
RpcApi.php:608 Avoid excessively long variable names like
$shippingAddressObject
RpcApi.php:671 Avoid unused local variables such as '$gateway'.
RpcApi.php:702 Avoid variables with short names like $q
RpcApi.php:707 Avoid variables with short names like $mm
30. PHP Copy Paster Detector
Just how lazy are you and your team?
31. -> % phpcpd lib/services/AMF_Checkout.php
phpcpd 1.3.3 by Sebastian Bergmann.
Found 2 exact clones with 52 duplicated lines
in 1 files:
- AMF_Checkout.php:60-68
AMF_Checkout.php:576-584
- AMF_Checkout.php:88-132
AMF_Checkout.php:602-646
7.21% duplicated lines out of 721 total lines
of code.
Time: 0 seconds, Memory: 6.50Mb
32. The Law of Demeter
The Law of Demeter for functions
states that any method of an object
should call only methods belonging to
itself, any parameters that were passed
in to the method, any objects it
created, and any directly held
component objects.
(from the best book EVER for programmers
^The Pragmatic Programmer ̄)
35. <?php
include 'test_bootstrap.php';
class FranchiseModelTest extends PHPUnit_Framework_TestCase
{
protected $_conn;
public function setUp()
{
$this->_conn = new PDO('pgsql:host=localhost;dbname=ibl_stats', 'stats', 'st@ts=Fun');
}
public function tearDown()
{
unset($this->_conn);
}
public function testSaveUpdatesDatabase()
{
$mapper = new IBLFranchiseMapper($this->_conn);
$franchise = new IBLFranchise();
$franchise->setId(25);
$franchise->setNickname('TST');
$franchise->setName('Test Team');
$franchise->setConference('Conference');
$franchise->setDivision('Division');
$franchise->setIp(0);
$mapper->save($franchise);
// Update existing model
$franchise->setIp(35);
$mapper->save($franchise);
// Reload Franchise record and compare them
$franchise2 = $mapper->findById($franchise->getId());
$this->assertEquals(35, $franchise2->getIp());
// Clean up the franchise
$mapper->delete($franchise);
}
}
36. public function save(IBLFranchise $franchise)
{
if ($this->findById($franchise->getId())) {
$this->_update($franchise);
} else {
$this->_insert($franchise);
}
}
protected function _insert(IBLFranchise $franchise)
{
try {
$sql = "
INSERT INTO franchises
(nickname, name, conference, division, ip, id)
VALUES(?, ?, ?, ?, ?, ?)";
$sth = $this->_conn->prepare($sql);
$binds = array(
$franchise->getNickname(),
$franchise->getName(),
$franchise->getConference(),
$franchise->getDivision(),
$franchise->getIp(),
$franchise->getId()
);
$sth->execute($binds);
} catch(PDOException $e) {
echo "A database problem occurred: " . $e-
>getMessage();
}
}
37. <?php
namespace Grumpy;
class Acl {
protected $_acls;
...
public function accessAlllowed()
{
$request = GrumpyContext::getRequest();
return ($this->_acls[$request->getUri()]
>= $_SESSION['user_level']);
}
}
// Meanwhile inside your controller
$acl = new GrumpyAcl();
if (!$acl->accessAllowed()) {
GrumpyView::render('access_denied.tmpl');
} else {
GrumpyView::render('show_stolen_cc.tmpl');
}
38. <?php
namespace Grumpy;
class Acl {
protected $_acls;
protected $_request;
protected $_userLevel;
...
public function __construct($request, $userLevel)
{
...
$this->_request = $request;
$this->_request = $userLevel;
}
public function accessAlllowed()
{
return ($this->_acls[$this->_request->getUri()]
>= $this->_userLevel);
}
}
// Meanwhile inside your controller
$acl = new GrumpyAcl();
if (!$acl->accessAllowed()) {
GrumpyView::render('access_denied.tmpl');
} else {
GrumpyView::render('show_stolen_cc.tmpl');
}
41. <?php
// Inside our bootstrap
...
// Create our container
$container = new Pimple();
// Inject our DB connection object for later reuse
$container['db_connection'] = function ($c) {
return new PDO(
'pgsql:host=localhost;dbname=ibl_stats',
'stats',
'st@ts=Fun'
);
};
// Then in a controller somewhere...
$mapper = new IBLFranchiseMapper($container['db_connection']);
42. <?php
// In the bootstrap, after having already added
// in the database connection
$container['franchise_mapper'] = function ($c) {
return new IBLFranchiseMapper($c['db_container']);
};
$container['game_mapper'] = function ($c) {
return new IBLGameMapper($c['db_container']);
};
44. <?php
class Omega
{
protected $foo;
protected $bar;
protected $bizz;
public function __construct($foo, $bar, $bizz)
{
$this->foo = $foo;
$this->bar = $bar;
$this->bizz = $bizz;
}
}
$dep1 = new Foo();
$dep2 = new Bar();
$dep3 = new Bizz();
$newOmega = new Omega($dep1, $dep2, $dep3);
45. <?php
class Omega
{
protected $foo;
protected $bar;
protected $bizz;
public function __construct($container)
{
$this->foo = $container['foo'];
$this->bar = $container['bar'];
$this->bizz = $container['biz'];
}
}
$container['foo'] = new Foo();
$container['bar'] = new Bar();
$container['bizz'] = new Bizz();
$newOmega = new Omega($container);
49. Mock Objects for
testing purposes
3rd-party web services
Accessing data sources
Environment independent
50. <?php
// Now here is our test case
include 'test_bootstrap.php';
class AclTest extends PHPUnit_Framework_TestCase
{
...
public function testDashboardAcl()
{
// Create a mock object
$testRequest = $this->getMock(
'GrumpyRequest',
array('getUri')
);
// Create our test response
$testRespect
->expects()
->method('getUri')
->with('/dashboard');
$testUserLevel = 3;
$testAcl = new GrumpyAcl($testRequest, $testUserLevel);
$response = $testAcl->accessAllowed();
$this->assertTrue($response);
}
}
51. Mock objects force you to
test code, not it¨s ability
to talk to outside sources
56. <?php
include 'test_bootstrap.php';
$conn = new PDO(
'pgsql:host=localhost;dbname=ibl_stats',
'stats',
'st@ts=Fun'
);
echo "Collecting all ?xtures for our league...n";
$mapper = new IBLFranchiseMapper($conn);
$allFranchises = $mapper->?ndAll();
echo "Writing franchise objects into ?xture ?le...n";
?le_put_contents('./?xtures/franchises.txt', serialize($allFranchises));
echo "Donen";
57. <?php
include './test_bootstrap.php';
class StandingsTest extends PHPUnit_Framework_TestCase
{
public function testGenerateRegular()
{
$data = ?le_get_contents('./?xtures/games.txt');
$testGames = unserialize($data);
$data = ?le_get_contents('./?xtures/franchises.txt');
$testFranchises = unserialize($data);
$testStandings = new IBLStandings($testGames, $testFranchises);
// Rest of the test is the same
}
}
58. Work as hard as you can
to remove the database
as a dependency for tests
60. <?php
// Assume $facebookUser is the object representing info
// about our user
$_SESSION['email'] = $facebookUser->getEmail();
$_SESSION['name'] =
$facebookUser->getFirstName() .
''.
$facebookUser->getLastName();
// In other parts of the app when I need to check if the user is
// authenticated properly
if (isset($_SESSION['email'])) {
// Execute the desired functionality
} else {
// Redirect user to log in with Facebook Connect
}
61. <?php
// New object that holds info about your Authenticated user
class AuthUser
{
...
public function check()
{
return (isset($_SESSION['email']));
}
}
// Then in the controller where you check authorization...
$authUser = new AuthUser();
if ($authUser->check() === true) {
// Execute the desired functionality
} else {
// Redirect user to log in with Facebook Connect
}
62. <?php
class AuthUser
{
protected $_sessionObject;
public function __construct($sessionContents)
{
$this->_sessionContents = $sessionContents;
}
public function check()
{
return (isset($this->_sessionContents['email']));
}
}
63. BONUS ROUND!
<?php
// Inside your unit test
$facebookMock = Mockery::mock(
'FacebookAPIFacebook',
array(
'getEmail' => 'test@littlehart.net',
'getName' => 'Testy McTesterson'
)
);
$sessionContents['email'] = $facebookMock->getEmail();
$auth = new AuthUser($sessionContents);
$this->assertTrue($auth->check());
Mockery - https://github.com/padraic/mockery
72. public function setUp()
{
// also include our libraries installed using Composer
include APP_ROOT . 'vendor/.composer/autoload.php';
// We are using Twig for templating
$loader = new Twig_Loader_Filesystem(APP_ROOT . 'templates');
$this->_twig = new Twig_Environment($loader);
$this->_twig = new Twig_Environment($loader, array('debug' => true));
$this->_twig->addExtension(new Twig_Extensions_Extension_Debug());
}
73. $gameMapper = new IBLGameMapper();
$franchiseMapper = new IBLFranchiseMapper();
$rotationMapper = new IBLRotationMapper();
$scheduleMapper = new IBLScheduleMapper();
82. Feature: Do a Google search
In order to find pages about Behat
As a user
I want to be able to use google.com to locate
search results
@javascript
Scenario: I search for Behat
Given I fill in "Behat github" for "q"
When I press "Google Search"
Then I should see "Trying to use Mink"