- Namespaces in php
- PSR-4 autoloader
- Nonces
- Shortcodes
Namespaces in php
Namespaces in php were introduced with version 5.3, they provide a great way to organize our code and also avoid naming conflicts
example
<?php
namespace main\controller
class Media{
}
?>
<?php
namespace main\view
class Media{
}
?>
Today or tommorow in project, we will run out of unique names to give to our classes and functions, so this is a great alternative instead of just prefixing everything.
PSR-4 Autoloader
PSR-4 autoloader is a standard that we can use to create our autoloader in the project. It uses nested namespaces and follows a specific directory structure.
We have to then import the autoloader only once in the main plugin file and we can autoload all our files. As for namespaces we have to use the full class name to access the classes.
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'movie_library\\includes';
// base directory for the namespace prefix
$base_dir = __DIR__;
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});
Nonce
Number used once, nonce is a hash value or some random digits, alphabets that we use to verify requests received are from legit sources and to protect our site from CSRF
To create nonce we can use wordpress inbuild function wp_create_nonce().
example :
$nonce = wp_create_nonce('csrf_token');
Then in our backend code, when we receive any request we can validate this nonce using wp_verifiy_nonce() function.
function save(){
if(!(isset($_GET['csrf_token'] &&
wp_verifiy_nonce($_GET['csrf_token], 'csrf_token) ){
return;
}
}
ShortCode API
Shortcodes in wordpress are used to render some content on the front end dynamically. they are writter as [directors_list]
The wordpress finds this shorcode if it is registered or not and call the function connected to it which will return some content.
This content will then be displayed at the place of the shortcode.
to register a shortcode we have to use:
function register_shortcodes(){
add_shortcode('recent-posts', 'directors_list_function');
}
Then we also have to define the callback which is going to give the content
function directors_list_function() {
//logic to get all directors
return $directors;
}
Leave a Reply