example:
$CONF = parse_ini_file('cfg.ini', true);
$EmailUN = $CONF['EM']['key01'];
$EmailPW = $CONF['EM']['key02'];
$EmailTO = $CONF['EM']['key03'];
$SMSAPI = $CONF['SMS']['key01'];
$SMSUN = $CONF['SMS']['key02'];
$SMSPW = $CONF['SMS']['key03'];
$SMSNUM = $CONF['SMS']['key04'];
is there a more effective/elegant way to import this data? i want to learn best practices while im still learning. i dont want to fill up the whole top of my php doc with objects calling for keys. if this is a duplicate i apologize in advance.
One approach would be a helper function that accesses your configuration.
If for example you wanted to access your configuration like this:
config('SMS.key01');
You could define the config function as:
function config(string $key)
{
static $config = parse_ini_file('cfg.ini', true);
$curr = $config;
foreach(explode('.', $key) as $segment) {
if(!isset($curr[$segment]) {
return null;
} else if(is_array($curr[$segment])) {
$curr = $curr[$segment];
continue;
}
return $curr[$segment];
}
}
The above is a minimal example roughly based on Laravel's config and array_get helpers. Your helper function would likely need to be implemented differently in the context of your application or framework.
The main advantage of this approach is that all of the implementation details of how your configuration is stored and accessed is contained within the function. What you are doing right now bleeds low level implementation details into the rest of your code.
Related
I have a database that holds several basis configuration settings for my site. The idea is to pull the values from the database and then make the values accessible globally. I also would like to implement $this->cachePage(DAY); to make sure the site is not constantly asking for configurations settings.
This is mysql table
I have put the following code into public function initController method of the
BaseController:
$global_app_settings = array();
$this->AppSettingModel = new \App\Models\AppSettingModel;
$app_settings = $this->AppSettingModel->getAppSettings();
foreach ($app_settings as $row) {
$global_app_settings[$row->app_setting_key] = $row->app_setting_value;
}
The above code works fine. If I print to screen, it produces the following;
Array
(
[dh_company_name] => A Big Company
[dh_phone_number] => +81-3-5555-5555
[dh_fax_number] => +81-3-5555-5556
)
My questions are as follows;
how can I make the array viable globally in my app?
Where can I add this? $this->cachePage(DAY);
It's simple actually.
public function loadGlobalSettings()
{
$globalSettings = cache('global_settings');
if (null === $globalSettings) {
$appSettingModel = model('\App\Models\AppSettingModel');
$app_settings = $appSettingModel->getAppSettings();
$globalSettings = [];
foreach ($app_settings as $row) {
$globalSettings[$row->app_setting_key] = $row->app_setting_value;
}
cache()->save('global_settings', $globalSettings, DAY*15);
}
return $globalSettings;
}
How it runs:
Try to get from cache.
If cache not exists (returned null), load model, get settings, then cache it.
Return settings array.
Have fun!
Define a protected variable in BaseController class and set it in initController
Put this in your controller
public function __construct()
{
this->cachePage(15);
}
For a long time I have a problem - should I reuse small parts of code and if so, how should I do it so it would be the best practice.
What I mean about small code is for example:
if (!is_array($table)) {
$table = array($table);
}
or
$x = explode("\n", $file_content);
$lines = array();
for ($i=0, $c = count($x); $i<$c; ++$i) {
$x[$i] = trim($x[$i]);
if ($x[$i] == '') {
continue;
}
$lines[] = $x[$i];
}
Such tiny parts of code may be used in many classes in one project but some of them are used also in many projects.
There are many possible solutions I think:
create simple function file and put them all reusable piece of codes as function, include them simple in project and use them whenever I want
create traits for those piece of codes and use them in classes
reuse code by simple copy paste or creating function in specific class (??)
other ?
I think all of those solutions have their pros and cons.
Question: What method should I use (if any) to reuse such code and why is this approach the best one in your opinion?
I think that "the best way" depends on many factors including the technology your applications use (procedural, OOP), versions of PHP they run on, etc. For example, traits are interesting and useful but they are available only since php 5.4.0 so using this tool to group your code snippets you will not be able to reuse them in systems running on earlier PHP versions. On the other hand if your app uses an OOP style and you organized your resuable small code snippets in functions, their usage may seem awkward in an OOP app and conflict with the function names in a particular class. In this case I think grouping your functions in classes would seem more natural.
Putting everything together, it seems that classes provide better tool for grouping resuable code snippets in terms outline above, namely backward compatibility with earlier PHP versions, avoiding function names conflicts, etc.) Personally I code mostly in OOP, so i have a Util class where I group small functions representing resuable pieces of code snippets that do not directly relate to each other and thus could not be logically groupped in other classes.
As mentioned already traits are a good thing. But might be a bit hard to manage after a while, and it might not be supported everywhere since its new.
What I do is to create Tool classes that have a lot small static functions, like:
class ArrayTools
{
static public function CheckArray($array)
{
if (!is_array($array))
{
$array = array($array);
}
return $array;
}
}
So you can call it with ArrayTools::CheckArray($array)
Please go with traits if your code mainly involves classes and objects.. As the the concept of traits exclusively focusses on code reuse ability.
Following are the code snippets which actually I use with Plain PHP projects, these code snippets are used from various frameworks good traits and best practices.
1.
The following code is used to check the environment in which your working, based on the environment you can set the some global variables, error reporting as so on.
if(!defined('ENVIRONMENT')){
define('ENVIRONMENT','DEVELOPMENT');
}
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'DEVELOPMENT':
case 'TESTING':
$base_url = 'http://localhost/project_name/';
error_reporting(E_ALL);
break;
case 'PRODUCTION':
$base_url = 'http://hostname/project_name/';
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
2.
/* This function is used to PRINT the ARRAY data in the pre formatted manner */
if (!function_exists('pr')) {
function pr($data) {
echo '<pre>', print_r($data), '</pre>';
}
}
3.
/* This function is used to Sanitize the user data and make data safe to insert into the database */
function sanitize($data) {
global $link;
$data = trim($data);
return htmlentities(strip_tags(mysqli_real_escape_string($link, $data)));
}
4.
/* Used to get the difference of 2 arrays
Returns the array with difference
*/
function multi_diff($arr1,$arr2){
$result = array();
foreach ($arr1 as $k=>$v){
if(!isset($arr2[$k])){
$result[$k] = $v;
} else {
if(is_array($v) && is_array($arr2[$k])){
$diff = multi_diff($v, $arr2[$k]);
if(!empty($diff))
$result[$k] = $diff;
}
}
}
return $result;
}
5.
/* This fnction is used to generate the random keys of specific length
Accepts parameter of certain length if not specified it will generate 20 bit length automatically
*/
function generate_random_key($length = 20) {
//Initializing the varialble
$keystring = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
$random_key = '';
for ($i = 0; $i < $length; $i++) {
$random_key.=$keystring[rand(0, strlen($keystring) - 1)];
}
//Return the randomly generated key
return $random_key;
}
6.
/* This function outputs the errors in ul>li format with unstyled
* To get the bullets styling remove class='list-unstyled' in <ul> tag */
function output_errors($errors){
$output = array();
foreach ($errors as $error) {
$output[] = '<li>'.$error.'</li>';
}
return '<ul class="list-unstyled">'.implode('', $output).'</ul>';
}
7.
/* Checks whether the user is loggedin else will redirect to the protectect page */
function protected_page(){
if(is_loggedin() === false){
// header('Location: protected.php');
header('Location: logout.php');
exit();
}
}
8.
/* If user tries to access the page directly accessing through the URL,
* If already loggedin then redirect him to any of the inner page
*/
function login_redirect(){
if(is_loggedin() === true){
header('Location: home.php');
}
}
9.
/* This function is used to check whether the user exists or not */
function email_exists($email){
/* Your Code */
}
/* This function is used to check whether the user isActive or not */
function is_active($email){
/* Your Code */
}
/* This function will get the userid from the email */
function userid_from_email($email) {
/* Your Code */
}
/* This fucntion is used to login the user based on the email-id and password */
function login($email,$password){
/* Your Code */
}
/* Check whether the USER is loggedin or not */
function is_loggedin(){
return (isset($_SESSION['userid'])) ? true : false;
}
Hope this helps you. Cheers!
I'm experimenting with php mvc and I'm stucked with the following issue. My request and router classes are really simple and I would like to extend theme to can handle controller calls from sub folders and to controller classes functions should be able to pick up url variables send it threw get and post.
my router looks as it follows
class Router{
public static function route(Request $request){
$controller = $request->getController().'Controller';
$method = $request->getMethod();
$args = $request->getArgs();
$controllerFile = __SITE_PATH.'/controllers/'.$controller.'.php';
if(is_readable($controllerFile)){
require_once $controllerFile;
$controller = new $controller;
if(!empty($args)){
call_user_func_array(array($controller,$method),$args);
}else{
call_user_func(array($controller,$method));
}
return;
}
throw new Exception('404 - '.$request->getController().'--Controller not found');
}
}
and Request class
private $_controller;
private $_method;
private $_args;
public function __construct(){
$parts = explode('/',$_SERVER['REQUEST_URI']);
$this->_controller = ($c = array_shift($parts))? $c: 'index';
$this->_method = ($c = array_shift($parts))? $c: 'index';
$this->_args = (isset($parts[0])) ? $parts : array();
}
public function getController(){
return $this->_controller;
}
public function getMethod(){
return $this->_method;
}
public function getArgs(){
return $this->_args;
}
}
The problem is:when I try to send threw ajax, variables to a controller method this are not recognized because of its url structure.
For example
index/ajax?mod_title=shop+marks&domain=example
is accepted just if it look
index/ajax/shop+mark/example
Your code contains what is known as an LFI vulnerability and is dangerous in its current state.
You should whitelist your what can be used as your $controller, as otherwise an attacker could try to specify something using NUL bytes and possibly going up a directory to include files that SHOULD NOT be ever included, such as /etc/passwd, a config file, whatever.
Your router is not safe for use; beware!
edit: example on whitelisting
$safe = array(
'ajax',
'somecontroller',
'foo',
'bar',
);
if(!in_array($this->_controller, $safe))
{
throw new Exception(); // replace me with your own error 404 stuff
}
Since your Request class uses a URI segments approach for identifying controller, action and arguments, global variables such as $_GET or $_REQUEST are not taken into account from within your Request.
What you need to do is to make some additions to your Request code. Specifically:
Remove the line:
$this->_args = (isset($parts[0])) ? $parts : array();
And add the following:
$all_parts = (isset($parts[0])) ? $parts : array();
$all_parts['get'] = $_GET;
$this->_args = $all_parts;
This way, $_GET (ie variables passed via the url) variables will be available in the actions called, as they will be in $args (they will be available as $args['get'] actually, which is the array that holds the $_GET vars, so you will be able to have access to domain=example by using $args['get']['domain']).
Ofcourse, you can add one more method in your Request class (e.g. query) that might look like that:
public function query($var = null)
{
if ($var === null)
{
return $_GET;
}
if ( ! isset($_GET[$var]) )
{
return FALSE;
}
return $_GET[$var];
}
This way, you can get a single variable from the url (e.g. $request->query('domain')) or the whole $_GET array ($request->query()).
That's because php will put "?mod_title=..." in the $_GET array automatically. Your getArgs() function should check for $_GET, $_POST or $_REQUEST.
If you're trying for a minimal MVC approach, have a look at rasmus' example: http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html
If your use case is going to get more complex, have a look at how Zend (http://framework.zend.com/manual/en/zend.controller.html) or Symfony (https://github.com/symfony/symfony/tree/master/src/Symfony/Component/Routing) do their stuff.
Choose any popular MVC to see how they implement it under the hood. In addition, spl_autoload_register and namespace are your friends.
Static properties make testing hard as you probably know. Is there no way to reset all static properties of a particular class back to their initial state? Ideally this would not require custom code for each class, but could be used in a general way by inheritance, or from outside of the class completely.
Please do not reply with something like, "don't use static properties". Thanks.
Assuming you're using PHPUnit:
See the PHPUnit Manual section about global state. Static members are covered by this if you have PHP 5.3 or higher. Static members are not part of serialization (in case you wonder).
See as well #backupGlobals and #backupStaticAttributes
No. PHP does not preserve that information.
I was toying around with ReflectionClass and ::getDefaultProperties and ::getStaticProperties, but they only return the current state.
You will have to create an array with the default values, then manually foreach over them and reset your class attributes.
I couldn't find any way to include or require classes or functions many times without getting an error.
Anyway, if you need to replace functions inside an structure you should make an array/ArrayObject of lamdas/inline functions (like javascript objects)
When you re import the array it will back to the original state.
$Animal = array(
'eat' => function($food) {/*...*/},
'run' => function($to_place) {/*...*/}
);
$Animal['eat'] = function($food) {/* new way to eat */}
I also managed to reset the state of static attributes by using Reflections. For this approach you need to use a convention attribute naming for default value of each type.
class MyStaticHolder {
public static $x_array = array();
public static $x_num = 0;
public static $x_str = '';
}
//change values
MyStaticHolder::$x_array = array(1,2,4);
MyStaticHolder::$x_num = -1.4;
MyStaticHolder::$x_str = 'sample-text';
function reset_static($class_name) {
$z = new ReflectionClass($class_name);
$properties = $z->getDefaultProperties();
print_r($properties);
foreach ($properties as $property_name => $value) {
$sufix = end(explode('_',$property_name));
switch ($sufix) {
case 'array':
$class_name::$$property_name = array();
break;
case 'num':
$class_name::$$property_name = 0;
break;
case 'str':
$class_name::$$property_name = '';
break;
default:
$class_name::$$property_name = null;
break;
}
}
}
reset_static('MyStaticHolder');
is there a class to handle $_REQUEST that makes the life of a php developer easier?
I want to handle the client requests easier.
I dont want to test with if(is_set($_REQUEST['blabla'])) {makesomthing();}
I wish there could be a solution like this.
class rpclike
{
public function getMember()
{
$memberid = $this->inputhandler['memberid'];
$member = $this->memberclass->getmember($memberid);
foreach($member as $mem)
{
echo $mem->id;
}
}
}
$rpc = new rpclike();
then if i call the rpclike from a javascript like this
Get member
Which class can do something like that?
It's not recommended that you use $_REQUEST as it poses security concerns. You should be using one of $_GET, $_POST, or $_COOKIE depending on what global request var you are trying to retrieve. Your best bet would be to have something like the following:
class input {
public static function get($key, $value = false) {
return (!empty($_GET[$key])) ? $_GET[$key] : $value;
}
public static function post($key, $value = false) {
return (!empty($_POST[$key])) ? $_POST[$key] : $value;
}
public static function cookie($key, $value = false) {
return (!empty($_COOKIE[$key])) ? $_COOKIE[$key] : $value;
}
}
You could then use the class like:
if (input::post('field', null) != null) {
}
or
if (input::get('field', false) != false) {
}
Although this still requires testing, you can explicitly set the return values in the event no data was set for the global variable.
PHP doesn't really have a default class structure that you can utilize in that kind of manner, as it's origins are in procedural-based programming.
It would be fairly trivial for you to create a class like that if you felt the need for it. However, you would really just be adding overhead. If the convenience of it is worth it for you, then you could utilize the __get() and __set() methods to handle existence checks for you.
The fact that you want to use this for handling client requests in an easier fashion is probably a good indicator that you should move to something like an MVC framework, which usually handle URLs and route them to appropriate methods for you automatically. Most PHP frameworks will do this for you already. For a nice overview on how the process commonly works, you could see how CodeIgniter does it.
Aside from the obvious security risks involved in this, it is feasible. It's a common pattern to use for steering requests in an MVC system.
Say you request index.php?class=User&method=ViewProfile
$module = new $_GET['class']();
if(!method_exists($module,$_GET['method']))
$module->$eventName();
I don't think so. Being able to invoke an arbitrary method would be a massive security hole.
Do something like:
url: /foo/bar?req=getMembers&memberid=22
Then you can do:
$request = $_GET['req'];
$request();
Slightly less dangerous version:
$req_methods = array(
getMembers => 'some_function',
saveMembers => 'another_function',
sendMessage => 'send_him_an_email'
);
$request = $_GET['req'];
$req_methods[$request]();