16. Databases
Many times your PHP code will use a database to persist information. You have a few options to connect and interact with your database. The recommended option until PHP 5.1.0 was to use native drivers such as mysqli, pgsql, mssql, etc.
Native drivers are great if you are only using one database in your application, but if, for example, you are using MySQL and a little bit of MSSQL, or you need to connect to an Oracle database, then you will not be able to use the same drivers. You’ll need to learn a brand new API for each database — and that can get silly.
16.1 PHPDoc
PHPDoc is an informal standard for commenting PHP code. There are a lot of different tags available. The full list of tags and examples can be found at the PHPDoc manual.
Below is an example of how you might document a class with a few methods;
1 <?php
2 /**
3 * @author A Name <a.name@example.com>
4 * @link https://docs.phpdoc.org/
5 */
6 class DateTimeHelper
7 {
8 /**
9 * @param mixed $anything Anything that we can convert to a \DateTime object
10 *
11 * @throws \InvalidArgumentException
12 *
13 * @return \DateTime
14 */
15 public function dateTimeFromAnything($anything)
16 {
17 $type = gettype($anything);
18
19 switch ($type) {
20 // Some code that tries to return a \DateTime object
21 }
22
23 throw new \InvalidArgumentException(
24 "Failed Converting param of type '{$type}' to DateTime object"
25 );
26 }
27
28 /**
29 * @param mixed $date Anything that we can convert to a \DateTime object
30 *
31 * @return void
32 */
33 public function printISO8601Date($date)
34 {
35 echo $this->dateTimeFromAnything($date)->format('c');
36 }
37
38 /**
39 * @param mixed $date Anything that we can convert to a \DateTime object
40 */
41 public function printRFC2822Date($date)
42 {
43 echo $this->dateTimeFromAnything($date)->format('r');
44 }
45 }
The documentation for the class as a whole has the @author tag and a @link tag. The @author tag is used to document the author of the code and can be repeated for documenting several authors. The @link tag is used to link to a website indicating a relationship between the website and the code.
Inside the class, the first method has a @param tag documenting the type, name and description of the parameter being passed to the method. Additionally it has the @return and @throws tags for documenting the return type, and any exceptions that could be thrown respectively.
The second and third methods are very similar and have a single @param tag as did the first method. The important
difference between the second and third methods’ doc block is the inclusion/exclusion of the @return tag.
@return void explicitly informs us that there is no return; historically omitting the @return void statement also results in the same (no return) action.