Memo - PHP

This is one of my memos about PHP language.

Memos are used for recording the problems I encountered during programming and its solutions. I also write down something that is hard to remember for myself.

Basic

Array

# Random get $num of entities from $array
array_rand($array, $num);

Long long string

Heredoc

$name = Silver;
echo <<<EOT
Hello, {$name}!
EOT;
/* Hello, Silver! */

Nowdoc

$name = Silver;
echo <<<EOT
Hello, {$name}!
EOT;
/* Hello, {$name}! */

Pass by reference

Passing by Reference

foreach ($array as &$item) {
    // Do something to $item here will change $array too
}

function foo(&$var)
{
    $var++;
}
$a=5;
foo($a);
// $a is 6 here

Error processing

// Traceback of errors
debug_print_backtrace();

Database

mysqli

MySQL Improved Extension

/*
* MySQL Query using mysqli
* http://php.net/manual/en/book.mysqli.php
*/
<?php
include 'vendor/autoload.php';

$mysqli = new mysqli("localhost", "root", "", "example");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT * FROM contacts LIMIT 10")) {
    printf("Select returned %d rows.\n", $result->num_rows);
    while ($row = $result->fetch_assoc()) {
        $person = array(
            'name' => $row['name'],
            'email' => $row['email']
        );
        $persons[] = $person;
    }
    /* free result set */
    $result->close();
}

d($persons);

$mysqli->close();
?>

IO

Script arguments

  • $argv — Array of arguments passed to script
  • getopt — Gets options from the command line argument list

Composer

Custom composer package

Reference:

The complete process is showing below.

Short list

  1. Make your library git available.
  2. Create a composer.json in the root of your library and fill it
  3. Done, now we can require it in our project

Detail

Package Setup:

Suppose you already have a library, like this:

└── src
    └── haha
        └── Hello.php

You need to create a composer.json:

├── README.md
├── composer.json
└── src
    └── haha
        └── Hello.php

The composer.json should have these things at least:

  • name - Define the name of this package. The whole repository will be cloned into /vendor/{name}/
  • autoload - Define the autoload method to autoload your library when some project use it.
    • autoload have multiple ways to define, see this autoload document for detail.
    • if your package already have autoload.php itself, just use "files": [ "path/to/autoload.php" ]
  • You can also define your dependency with a "require" key.
{
    "name": "silverhugh/toy",
    "autoload": {
        "psr-4": {
            "happy\\": "src/"
        }
    }
}

And your package is ready!

Project Setup:

You can start from an empty project without any files. And then, create a composer.json in this empty playground.

Fill it just like this one:

  • repositories - Make composer to know where to find your package if your package can’t be found in packagist
  • silverhugh/toy - This must exactly the same name of the library defined in the composer.json
  • dev-master - If you want exactly the latest code of this git repository
  • psy-psysh - This php cli is just awesome
{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/example/example.git"
        }
    ],
    "require": {
        "silverhugh/toy": "dev-master",
        "psy/psysh": "0.8.11"
    }
}

Just composer update!

If you haven’t got a composer, see the installation guide of composer

Now all things has been setup. The problem comes to how to use this custom package.

I will choose two ways of using the class of package. The difference is just the different way you autoload your library.

Suppose the Hello.php contains these code:

<?php

namespace happy\haha;

class BigHello
{
    public static function Hello()
    {
        return "Awesome! You just make composer works.";
    }
}

Execute this code in the shell under the root of your project, and it just works!

vendor/bin/psysh
Psy Shell v0.8.11 (PHP 7.1.8  cli) by Justin Hileman
>>> happy\haha\BigHello::Hello();
=> "Awesome! You just make composer works."
>>>

Categories: ,

Updated:

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...