get_called_class vs get_class string get_called_class ( void ) // Gets the name of the class the static method is called in. string get_class ([ object $object = NULL ] ) // Gets the name of the class of the given object. -------- get_called_class class foo { static public function test() { var_dump(get_called_class()); } } class bar extends foo { } foo::test(); // string(3) "foo" bar::test(); // string(3) "bar" --------- get_class • get_class($this) • get_class($bar) class foo { function name() { echo "My name is " , get_class($this) , "\n"; } } $bar = new foo(); // create an object echo "Its name is " , get_class($bar) , "\n"; // external call // Its name is foo $bar->name(); // internal call // My name is foo ---------- abstract class bar { public function __construct() { var_dump(get_class($this)); var_dump(get_class()); } } class foo extends bar { } new foo; string(3) "foo" string(3) "bar"
Author: dreboard
Counting a PHP stdClass Object
$obj = new stdClass; $obj->one = 1; $obj->two = 2; $vars = get_object_vars($obj); echo count($vars);
PHP Errors and Logging Settings
PHP .ini file
Locate the section “Error handling and logging”, This directive informs PHP of which errors, warnings and notices you would like it to take action for.
You will see and be able to alter these config settings
error_reporting = E_ALL display_errors = On display_startup_errors = On log_errors = On log_errors_max_len = 1024 ignore_repeated_errors = Off ignore_repeated_source = Off report_memleaks = On track_errors = Off html_errors = On
Error Reporting
This directive informs PHP of which errors, warnings and notices you would like it to take action for.
To show only errors, (no warnings or notices)
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR
If you do only display errors, you will not be able to see common run time notices and warnings such as
NOTICE Undefined variable: var on line number 2
Display Errors
Just because error reporting is turned on, you wont be able to see the errors unless the display_errors flag has the on value
To show only errors, (no warnings or notices)
display_errors = On
Prevent Files from being cached
Using php
<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/site-script.js?<?php echo time(); ?>"></script> // OR <link href="/stylesheet.css?<?php echo filemtime('mycss.css'); ?>" rel="stylesheet" type="text/css" /> // OR /** * Given a file, /css/base.css, replaces it with a string containing the * file's mtime, /css/base.1221534296.css. * * @param $file The file to be loaded. Must be an absolute path */ function auto_version($file) { if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) return $file; $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file); return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file); } <link rel="stylesheet" href="/css/base.css" type="text/css" />
// OR // OR /** * Given a file, /css/base.css, replaces it with a string containing the * file's mtime, /css/base.1221534296.css. * * @param $file The file to be loaded. Must be an absolute path */ function auto_version($file) { if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) return $file; $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file); return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file); }
Using javascript
Using .htaccess
FileETag None Header unset ETag Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
Using GIT
/** * Get the hash of the current git HEAD * @param str $branch The git branch to check * @return mixed Either the hash or a boolean false */ public static function get_commit( $branch='master' ) { if ( $hash = file_get_contents( sprintf( '.git/refs/heads/%s', $branch ) ) ) { return $hash; } else { return time(); } }
Prevent Viewing of .htaccess files
Inside your .htaccess file add:
order allow,deny
deny from all
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
Create a MySQL users Table
Code for Creating `users` Table inside PhpMyAdmin
CREATE TABLE `users` (
`id` int NOT NULL AUTO_INCREMENT,
`employee_id` int DEFAULT NULL,
`user_type` varchar(50) DEFAULT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `users` (`employee_id`, `user_type`, `username`, `password`) VALUES
(NULL, 'SUPER ADMIN', 'admin', 'admin'),
(1, 'NORMAL', 'robin', 'robin'),
(2, 'ADMIN', 'taylor', 'taylor'),
(3, 'ADMIN', 'vivian', 'vivian'),
(4, 'NORMAL', 'harry', 'harry'),
(7, 'ADMIN', 'melinda', 'melinda'),
(8, 'NORMAL', 'harley', 'harley');
Command line code for Creating `user` from a users.sql file
mysql> use db_name;
mysql> source users.sql;
Slim 3 API Part 2 DB Configurations
Database configuration
Create the file src/settings.php inside your api folder and place the following code
"db" => [
"host" => "locahost",
"dbname" => "your-database-name",
"user" => "your-mysql-user",
"pass" => "your-mysql-password"
],
Create the file src/dependencies.php inside your api folder and place the following code
$container['db'] = function ($c) {
$settings = $c->get('settings')['db']; // From src/settings.php
$pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'],
$settings['user'], $settings['pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
};
This is injecting the database object into container, and you can now access all users
** For creating the users table see Create users table post
require __DIR__ . '/vendor/autoload.php';
$app = new Slim\App;
$app->get('/', function ($request, $response) {
return 'hello world';
});
$app->post('/postit', function ($request, $response) {
$input = $request->getParsedBody();
return $this->response->withJson($input);
});
$app->get('/all', function ($request, $response, $args) {
$sth = $this->db->prepare("SELECT * FROM users");
$sth->execute();
$users = $sth->fetchAll();
return $this->response->withJson($users);
});
$app->run();
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