Slim 3 PHP Routes Return 404 Page Not Found

If your routes give you a 404 error when removing the localhost:8080/index.php/xxx

Ensure that your 000-default.conf or whatever you name it has AllowOverride All


    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/public

    ServerName "dev.local"
    ServerAlias "www.dev.local"

    
        Options -Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
    ErrorLog /var/www/html/logs/error.log
    CustomLog /var/www/html/logs/access.log combined

Ensure that a .htaccess file is in the same folder as the index.php, and the contents are


    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [qsappend,last]

Restart/reload apache apache

sudo service apache2 reload
service apache2 restart
service httpd reload
//For whatever flavor your running

Slim 3 API Part 1 Hello World

Installation

1. Create your api folder
2. Make sure you download the composer.phar file into the folder.
3. Open a shell script, cd to your new api folder and type

composer require slim/slim "^3.0"
//or
php composer.phar require slim/slim "^3.0"

Basic Setup and Routing

Now you should only see your composer.lock, composer.json and a vendor directory. Create index.php and place the following code inside.

get('/', function ($request, $response) {
    return 'hello world';
});

$app->run();

Preview

Go back to the terminal and type

php -S localhost:8000

in the browser visit, http://localhost:8000/ you should see “hello world”

API calls with Slim

GET is used for reading and retrieving data.
POST is used for inserting data.
PUT is used for updating data.
DELETE is used for deleting data.

POST

get('/', function ($request, $response) {
    return 'hello world';
});

 $app->post('/postit', function ($request, $response) {
     $input = $request->getParsedBody();
     return $this->response->withJson($input);
 });

$app->run();

You can then create a form but we will simulate a form post by using curl.
on the command line run

curl -d "param1=value1¶m2=value2" -X POST http://localhost:8000/postit

You should see

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100    64  100    37  100    27     45     33 --:--:-- --:--:-- --:--:--    78{"param1":"value1","param2":"value2"}

Track number of objects created from a class

To track the existing number of objects of a given class create a static property to hold the current value, updated with the constructor. When unsetting an object, the __destruct() method will update the object count. You can create new instances without hitting the constructor via clone and deleted with unset()


/*
* Class TrackableClass 
*/
class TrackableClass {
    public static $instances = 0;

    public function __construct() 
    {
        self::$instances++;
    }

    public function __destruct() 
    {
        self::$instances--;
    }
	
    public function __clone() 
    {
	self::$instances++;
    }
	
    public function __unset($name)
    {
        self::$instances--;
    }
	
}

$obj1 = new TrackableClass();
$obj2 = new TrackableClass();
$obj3 = new TrackableClass();
$obj4 = clone $obj3;

echo TrackableClass::$instances; // 4
unset($obj4);
echo TrackableClass::$instances; // 3
$obj3 = null;
echo TrackableClass::$instances; // 2

PHP Method Chaining

Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results


/*
* ChainableClass
* cascading-by-chaining by returning this
*/
class ChainableClass {
  function methodOne() {
    echo __METHOD__.' called, ';
    return $this;
  }
  function methodTwo() {
    echo __METHOD__.' called';
    return $this;
  }
}
(new ChainableClass)->methodOne()->methodTwo();
// Result: BaseClass::methodOne called, BaseClass::methodTwo called

With Static


/*
* ChainableClass
* cascading-by-chaining by returning self
*/
class ChainableClassStatic {
  public static $prop;

  public static function ChainableStaticMethod()
  {
    self::$prop = 'Chainable Class String';
    return new self;
  }

  public function regularMethod()
  {
    echo self::$prop;
  }
}
ChainableClassStatic::ChainableStaticMethod()->regularMethod();
// Result: Chainable Class String