mirror of
https://github.com/codeguy/php-the-right-way.git
synced 2025-08-20 12:21:40 +02:00
Fix line wrapping consistency - round 1
Comply with the 'wrap at 120 chars' style rule stated in the contributing.md document
This commit is contained in:
@@ -5,9 +5,9 @@ title: Design Patterns
|
||||
|
||||
# Design Patterns
|
||||
|
||||
There are numerous ways to structure the code and project for your web application, and you can put as much or as little
|
||||
thought as you like into architecting. But it is usually a good idea to follow common patterns because it will make
|
||||
your code easier to manage and easier for others to understand.
|
||||
There are numerous ways to structure the code and project for your web application, and you can put as much or as
|
||||
little thought as you like into architecting. But it is usually a good idea to follow common patterns because it will
|
||||
make your code easier to manage and easier for others to understand.
|
||||
|
||||
* [Architectural pattern on Wikipedia](https://en.wikipedia.org/wiki/Architectural_pattern)
|
||||
* [Software design pattern on Wikipedia](https://en.wikipedia.org/wiki/Software_design_pattern)
|
||||
@@ -15,8 +15,8 @@ your code easier to manage and easier for others to understand.
|
||||
|
||||
## Factory
|
||||
|
||||
One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates
|
||||
the object you want to use. Consider the following example of the factory pattern:
|
||||
One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the
|
||||
object you want to use. Consider the following example of the factory pattern:
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
@@ -53,9 +53,9 @@ print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron"
|
||||
|
||||
This code uses a factory to create the Automobile object. There are two possible benefits to building your code this
|
||||
way; the first is that if you need to change, rename, or replace the Automobile class later on you can do so and you
|
||||
will only have to modify the code in the factory, instead of every place in your project that uses the Automobile
|
||||
class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in
|
||||
the factory, instead of repeating it every time you want to create a new instance.
|
||||
will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class.
|
||||
The second possible benefit is that if creating the object is a complicated job you can do all of the work in the
|
||||
factory, instead of repeating it every time you want to create a new instance.
|
||||
|
||||
Using the factory pattern isn't always necessary (or wise). The example code used here is so simple that a factory
|
||||
would simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save
|
||||
@@ -65,8 +65,8 @@ yourself a lot of trouble down the road by using factories.
|
||||
|
||||
## Singleton
|
||||
|
||||
When designing web applications, it often makes sense conceptually and architecturally to allow access to one and
|
||||
only one instance of a particular class. The singleton pattern enables us to do this.
|
||||
When designing web applications, it often makes sense conceptually and architecturally to allow access to one and only
|
||||
one instance of a particular class. The singleton pattern enables us to do this.
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
@@ -144,20 +144,21 @@ request lifecycle in a web application. This typically occurs when we have globa
|
||||
class) or a shared resource (such as an event queue).
|
||||
|
||||
You should be wary when using the singleton pattern, as by its very nature it introduces global state into your
|
||||
application, reducing testability. In most cases, dependency injection can (and should) be used in place of a
|
||||
singleton class. Using dependency injection means that we do not introduce unnecessary coupling into the design of our
|
||||
application, reducing testability. In most cases, dependency injection can (and should) be used in place of a singleton
|
||||
class. Using dependency injection means that we do not introduce unnecessary coupling into the design of our
|
||||
application, as the object using the shared or global resource requires no knowledge of a concretely defined class.
|
||||
|
||||
* [Singleton pattern on Wikipedia](https://en.wikipedia.org/wiki/Singleton_pattern)
|
||||
|
||||
## Strategy
|
||||
|
||||
With the strategy pattern you encapsulate specific families of algorithms allowing the client class responsible for
|
||||
instantiating a particular algorithm to have no knowledge of the actual implementation.
|
||||
There are several variations on the strategy pattern, the simplest of which is outlined below:
|
||||
With the strategy pattern you encapsulate specific families of algorithms allowing the client class responsible for
|
||||
instantiating a particular algorithm to have no knowledge of the actual implementation. There are several variations on
|
||||
the strategy pattern, the simplest of which is outlined below:
|
||||
|
||||
This first code snippet outlines a family of algorithms; you may want a serialized array, some JSON or maybe just an
|
||||
array of data:
|
||||
|
||||
This first code snippet outlines a family of algorithms; you may want a serialized array, some JSON or maybe
|
||||
just an array of data:
|
||||
{% highlight php %}
|
||||
<?php
|
||||
|
||||
@@ -191,7 +192,7 @@ class ArrayOutput implements OutputInterface
|
||||
}
|
||||
{% endhighlight %}
|
||||
|
||||
By encapsulating the above algorithms you are making it nice and clear in your code that other developers can easily
|
||||
By encapsulating the above algorithms you are making it nice and clear in your code that other developers can easily
|
||||
add new output types without affecting the client code.
|
||||
|
||||
You will see how each concrete 'output' class implements an OutputInterface - this serves two purposes, primarily it
|
||||
@@ -201,6 +202,7 @@ this case 'OutputInterface'.
|
||||
|
||||
The next snippet of code outlines how a calling client class might use one of these algorithms and even better set the
|
||||
behaviour required at runtime:
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
class SomeClient
|
||||
@@ -222,6 +224,7 @@ class SomeClient
|
||||
The calling client class above has a private property which must be set at runtime and be of type 'OutputInterface'
|
||||
once this property is set a call to loadOutput() will call the load() method in the concrete class of the output type
|
||||
that has been set.
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
$client = new SomeClient();
|
||||
@@ -249,7 +252,11 @@ and gives you a central place to hook in code that should be run for every reque
|
||||
|
||||
## Model-View-Controller
|
||||
|
||||
The model-view-controller (MVC) pattern and its relatives HMVC and MVVM lets you break up code into logical objects that serve very specific purposes. Models serve as a data access layer where data is fetched and returned in formats usable throughout your application. Controllers handle the request, process the data returned from models and load views to send in the response. And views are display templates (markup, xml, etc) that are sent in the response to the web browser.
|
||||
The model-view-controller (MVC) pattern and its relatives HMVC and MVVM lets you break up code into logical objects
|
||||
that serve very specific purposes. Models serve as a data access layer where data is fetched and returned in formats
|
||||
usable throughout your application. Controllers handle the request, process the data returned from models and load
|
||||
views to send in the response. And views are display templates (markup, xml, etc) that are sent in the response to the
|
||||
web browser.
|
||||
|
||||
MVC is the most common architectural pattern used in the popular [PHP frameworks](https://github.com/codeguy/php-the-right-way/wiki/Frameworks).
|
||||
|
||||
|
@@ -5,16 +5,16 @@ title: Functional Programming in PHP
|
||||
|
||||
# Functional Programming in PHP
|
||||
|
||||
PHP supports first-class functions, meaning that a function can be assigned to a variable. Both user-defined and built-in
|
||||
functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to other
|
||||
functions and a function can return other functions (a feature called higher-order functions).
|
||||
PHP supports first-class functions, meaning that a function can be assigned to a variable. Both user-defined and
|
||||
built-in functions can be referenced by a variable and invoked dynamically. Functions can be passed as arguments to
|
||||
other functions and a function can return other functions (a feature called higher-order functions).
|
||||
|
||||
Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code focus
|
||||
is on iteration.
|
||||
Recursion, a feature that allows a function to call itself, is supported by the language, but most of the PHP code
|
||||
focus is on iteration.
|
||||
|
||||
Anonymous functions (with support for closures) have been present since PHP 5.3 (2009).
|
||||
|
||||
PHP 5.4 added the ability to bind closures to an object's scope and also improved support for callables such that they
|
||||
PHP 5.4 added the ability to bind closures to an object's scope and also improved support for callables such that they
|
||||
can be used interchangeably with anonymous functions in almost all cases.
|
||||
|
||||
The most common usage of higher-order functions is when implementing a strategy pattern. The built-in `array_filter`
|
||||
@@ -42,7 +42,7 @@ print_r($output);
|
||||
{% endhighlight %}
|
||||
|
||||
A closure is an anonymous function that can access variables imported from the outside scope without using any global
|
||||
variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is
|
||||
variables. Theoretically, a closure is a function with some arguments closed (e.g. fixed) by the environment when it is
|
||||
defined. Closures can work around variable scope restrictions in a clean way.
|
||||
|
||||
In the next example we use closures to define a function returning a single filter function for `array_filter`, out of
|
||||
@@ -70,12 +70,12 @@ $output = array_filter($input, criteria_greater_than(3));
|
||||
print_r($output); // items > 3
|
||||
{% endhighlight %}
|
||||
|
||||
Each filter function in the family accepts only elements greater than some minimum value. Single filter returned by
|
||||
`criteria_greater_than` is a closure with `$min` argument closed by the value in the scope (given as an argument when
|
||||
Each filter function in the family accepts only elements greater than some minimum value. Single filter returned by
|
||||
`criteria_greater_than` is a closure with `$min` argument closed by the value in the scope (given as an argument when
|
||||
`criteria_greater_than` is called).
|
||||
|
||||
Early binding is used by default for importing `$min` variable into the created function. For true closures with late
|
||||
binding one should use a reference when importing. Imagine a templating or input validation library, where closure is
|
||||
binding one should use a reference when importing. Imagine a templating or input validation library, where closure is
|
||||
defined to capture variables in scope and access them later when the anonymous function is evaluated.
|
||||
|
||||
* [Read about Anonymous functions][anonymous-functions]
|
||||
|
@@ -104,8 +104,8 @@ function test($a)
|
||||
|
||||
## Global namespace
|
||||
|
||||
When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this,
|
||||
refer to the global function by using a backslash before the function name.
|
||||
When using namespaces, you may find that internal functions are hidden by functions you wrote. To fix this, refer to
|
||||
the global function by using a backslash before the function name.
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
@@ -153,17 +153,17 @@ $a = 'Multi-line example' // concatenation operator (.)
|
||||
|
||||
### String types
|
||||
|
||||
Strings are a series of characters, which should sound fairly simple. That said, there are a few different types
|
||||
of strings and they offer slightly different syntax, with slightly different behaviors.
|
||||
Strings are a series of characters, which should sound fairly simple. That said, there are a few different types of
|
||||
strings and they offer slightly different syntax, with slightly different behaviors.
|
||||
|
||||
#### Single quotes
|
||||
|
||||
Single quotes are used to denote a "literal string". Literal strings do not attempt to parse special characters
|
||||
or variables.
|
||||
Single quotes are used to denote a "literal string". Literal strings do not attempt to parse special characters or
|
||||
variables.
|
||||
|
||||
If using single quotes, you could enter a variable name into a string like so: `'some $thing'`, and you would
|
||||
see the exact output of `some $thing`. If using double quotes, that would try to evaluate the `$thing` variable
|
||||
name and show errors if no variable was found.
|
||||
If using single quotes, you could enter a variable name into a string like so: `'some $thing'`, and you would see the
|
||||
exact output of `some $thing`. If using double quotes, that would try to evaluate the `$thing` variable name and show
|
||||
errors if no variable was found.
|
||||
|
||||
|
||||
{% highlight php %}
|
||||
@@ -182,7 +182,7 @@ echo 'This is my string, look at how pretty it is.'; // no need to parse a si
|
||||
#### Double quotes
|
||||
|
||||
Double quotes are the Swiss Army Knife of strings. They will not only parse variables as mentioned above, but all sorts
|
||||
of special characters, like `\n` for newline, `\t` for a tab, etc.
|
||||
of special characters, like `\n` for newline, `\t` for a tab, etc.
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
@@ -204,8 +204,8 @@ $juice = 'plum';
|
||||
echo "I like $juice juice"; // Output: I like plum juice
|
||||
{% endhighlight %}
|
||||
|
||||
When using interpolation, it is often the case that the variable will be touching another character.
|
||||
This will result in some confusion as to what is the name of the variable, and what is a literal character.
|
||||
When using interpolation, it is often the case that the variable will be touching another character. This will result
|
||||
in some confusion as to what is the name of the variable, and what is a literal character.
|
||||
|
||||
To fix this problem, wrap the variable within a pair of curly brackets.
|
||||
|
||||
@@ -285,21 +285,21 @@ EOD; // closing 'EOD' must be on it's own line, and to th
|
||||
|
||||
### Which is quicker?
|
||||
|
||||
There is a myth floating around that single quote strings are fractionally quicker than double quote strings. This
|
||||
is fundamentally not true.
|
||||
There is a myth floating around that single quote strings are fractionally quicker than double quote strings. This is
|
||||
fundamentally not true.
|
||||
|
||||
If you are defining a single string and not trying to concatenate values or anything complicated, then either a single or
|
||||
double quoted string will be entirely identical. Neither are quicker.
|
||||
If you are defining a single string and not trying to concatenate values or anything complicated, then either a single
|
||||
or double quoted string will be entirely identical. Neither are quicker.
|
||||
|
||||
If you are concatenating multiple strings of any type, or interpolate values into a double quoted string, then the results can
|
||||
vary. If you are working with a small number of values, concatenation is minutely faster. With a lot of values, interpolating
|
||||
is minutely faster.
|
||||
If you are concatenating multiple strings of any type, or interpolate values into a double quoted string, then the
|
||||
results can vary. If you are working with a small number of values, concatenation is minutely faster. With a lot of
|
||||
values, interpolating is minutely faster.
|
||||
|
||||
Regardless of what you are doing with strings, none of the types will ever have any noticable impact on your application.
|
||||
Trying to rewrite code to use one or the other is always an exercise in futility, so avoid this micro-optimization unless you really
|
||||
understand the meaning and impact of the differences.
|
||||
Regardless of what you are doing with strings, none of the types will ever have any noticable impact on your
|
||||
application. Trying to rewrite code to use one or the other is always an exercise in futility, so avoid this micro-
|
||||
optimization unless you really understand the meaning and impact of the differences.
|
||||
|
||||
[Disproving the Single Quotes Performance Myth]: http://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html
|
||||
* [Disproving the Single Quotes Performance Myth](http://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html)
|
||||
|
||||
|
||||
## Ternary operators
|
||||
@@ -334,7 +334,8 @@ return ($a == 5) ? 'yay' : 'nope'; // this example will return 'yay'
|
||||
|
||||
{% endhighlight %}
|
||||
|
||||
It should be noted that you do not need to use a ternary operator for returning a boolean value. An example of this would be.
|
||||
It should be noted that you do not need to use a ternary operator for returning a boolean value. An example of this
|
||||
would be.
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
@@ -352,7 +353,8 @@ This can also be said for all operations(===, !==, !=, == etc).
|
||||
|
||||
#### Utilising brackets with ternary operators for form and function
|
||||
|
||||
When utilising a ternary operator, brackets can play their part to improve code readability and also to include unions within blocks of statements. An example of when there is no requirement to use bracketing is:
|
||||
When utilising a ternary operator, brackets can play their part to improve code readability and also to include unions
|
||||
within blocks of statements. An example of when there is no requirement to use bracketing is:
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
@@ -365,7 +367,9 @@ $a = 3;
|
||||
return $a == 3 ? "yay" : "nope"; // return yay or nope if $a == 3
|
||||
{% endhighlight %}
|
||||
|
||||
Bracketing also affords us the capability of creating unions within a statement block where the block will be checked as a whole. Such as this example below which will return true if both ($a == 3 and $b == 4) are true and $c == 5 is also true.
|
||||
Bracketing also affords us the capability of creating unions within a statement block where the block will be checked
|
||||
as a whole. Such as this example below which will return true if both ($a == 3 and $b == 4) are true and $c == 5 is
|
||||
also true.
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
@@ -384,9 +388,8 @@ return ($a != 3 && $b != 4) || $c == 5;
|
||||
## Variable declarations
|
||||
|
||||
At times, coders attempt to make their code "cleaner" by declaring predefined variables with a different name. What
|
||||
this does in reality is to double the memory consumption of said script. For the example below, let us say
|
||||
an example string of text contains 1MB worth of data, by copying the variable you've increased the scripts execution to
|
||||
2MB.
|
||||
this does in reality is to double the memory consumption of said script. For the example below, let us say an example
|
||||
string of text contains 1MB worth of data, by copying the variable you've increased the scripts execution to 2MB.
|
||||
|
||||
{% highlight php %}
|
||||
<?php
|
||||
|
Reference in New Issue
Block a user