Static vs Non-static methods in PHP. what is faster?

As you know there are two types of methods in PHP classes: static and non-static. To be called a non-static method needs an instance of its class, and static method can be called without instantiating of the class. 

In the meantime there are two very common questions:

  • When to use non-static methods and when to use static methods?
  • Is there any performance difference between static and non-static methods?

These are very common dilemmas among PHP developers. Most of developers guess that static methods must work faster because there is no object instance with all its properties involved to the call. Sounds logical. Is that actually true?

As I already mentioned above, and as you already know, the main difference between static and non-static methods is that static methods do not need an instance of the class to be called in the code. It means that for static methods there is no need to create object and keep in the memory. So, at least we can save some memory which can also affect the performance

Some experiments

To test the performance of static and nonstatic methods let’s create two similar classes. The only difference will be how we call methods in the class.

 

Static class

<?php
set_time_limit(0);
Class Static0 {

	public static $counter = 0;
	
	public static function incrByTwo()
	{
		self::$counter = self::$counter + 2;
	}
}

Class Static1 extends Static0 {

	public static function incrByOne()
	{
		self::$counter = self::$counter + 1;
	}
	
	public static function incrByTwo()
	{
		parent::incrByTwo();
	}
}

$time_start = microtime(true);
for($i=0;$i<100000;$i++) {
	Static1::incrByOne();
	Static1::incrByTwo();
}

echo Static0::$counter ;
$time_end = microtime(true);
$time1 = $time_end - $time_start;
?>
Total execution time is <?php echo $time1;?>
Used memory: <?php echo memory_get_usage();?>

NonStatic class

<?php
set_time_limit(0);

Class Static0 {

	public $counter = 0;

	public function incrByTwo()
	{
		$this->counter = $this->counter + 2;
	}
}

Class Static1 extends Static0 {
	
	public function incrByOne()
	{
		$this->counter = $this->counter + 1;
	}
	
	public function incrByTwo()
	{
		parent::incrByTwo();
	}
}

$time_start = microtime(true);
$obj = new Static1();
for($i=0;$i<100000;$i++) {
	$obj->incrByOne();
	$obj->incrByTwo();
}

echo $obj->counter ;

$time_end = microtime(true);
$time1 = $time_end - $time_start;
?>

Total execution time is <?php echo $time1;?>
Used memory: <?php echo memory_get_usage();?>

Okay, now we know that static methods are indeed generally faster than non-static methods. And the difference in memory consumption doesn’t look significant at all…

So, use static methods everywhere now?

Not really. Short answer to this question would be: you don’t need an object and don’t need a non-static method if the method doesn’t interact with properties or methods in the class and its parents/children.

Yes, static methods look  faster. In the meantime, a lot of developers believe (and they have good reasons) that using static methods and properties break a lot of the power available to Object-Oriented code. They also mention that Unit testing is impossible using static methods.

Easily Develop Node.js and MongoDB Apps with Mongoose

Easily Develop Node.js and MongoDB Apps with Mongoose. Everything is simple for JSON. his is why you get popular stacks like the MEAN stack that uses Node, Express (a Node.js framework), MongoDB, and AngularJS.

What Is Mongoose?

mongoose is an object modeling package for Node that essentially works like an ORM that you would see in other languages (like Eloquent for Laravel).

Mongoose allows us to have access to the MongoDB commands for CRUD simply and easily. To use mongoose, make sure that you add it to you Node project by using the following command:

$ npm install mongoose --save

Now Include our project


var mongoose = require('mongoose');

Connect with mongo database


mongoose.connect('mongodb://localhost/test');

Before handle CRUD operation we will need Mongoose Model . It has include two options Schema and method. They represent documents which can be saved and retrieved from our database.

Sample User Model

module.exports = (function UserSchema() {

var mongoose = require(‘../db’).mongoose;
var UserRolesSchema = require(‘./UserRolesSchema’);
var UserLoginHistorySchema = require(‘./UserLoginHistorySchema’);
var uuid = require(‘uuid’);
var Schema = mongoose.Schema;
var RandomString = require(“randomstring”);

var mongoose = require(‘../db’).mongoose;

var schema = {
uuid: {
type: String,
unique: true,
default: uuid.v4()
},
email_address: {
default: null,
type: String,
unique: true,
required: true
},
password: {
required: true,
type: String,
minLength: [
5, “Password must be greater than 5 character”
],
maxLength: [
255, “Password must be less than 30 character”
]
},
email_hash: {
type: String,
default: RandomString.generate(),
unique: true
},
token: String,
profile: {
first_name: {
default: null,
type: String,
required: true,
message: “First name required”
},
last_name: {
default: null,
type: String,
required: true
},
date_of_birth: {type: Date, default: null},
gender: {
type: String,
enum: [‘male’, ‘female’]
},
photo_path: {
original: {
type: String,
default: ‘https://placeholdit.imgix.net/~text?txtsize=47&txt=Profile%20Photo&w=500&h=500’
},
thumbnail: {
type: String,
default: ‘https://placeholdit.imgix.net/~text?txtsize=20&txt=Profile%20Photo&w=200&h=200’
}
},
billing_address: {
street: {
type: String,
default: null
},
street_additional: {
type: String,
default: null
},
city: {
type: String,
default: null
},
state: {
type: String,
default: null
},

zip: {
type: Number,
default: null
},
country: {
type: String,
default: null
},
phone: {
type: String,
default: null
}
},
gateway_customer_id: {
name: {
type: String
},
customer_id: {
type: String
}
}
},
campaign: {
source: {type: String, default: null},
medium: {type: String, default: null},
identifier: {type: String},
organic: {type: Boolean},
paid: {type: Boolean}
},
is_active: {type: Boolean, default: false},
email_verified: {
type: Boolean,
default: false
},
role: {
type: String,
default: ‘user’,
required: true
},
security: {
questions: {
question_1: {type: String, default: null},
answer_1: {type: String, default: null},
question_2: {type: String, default: null},
answer_2: {type: String, default: null}
}
},
password_reset: {
token: {
type: String,
default: null
},
last_token_generated: {
type: Date
},
token_validity: {
type: String
},
password_changed: {
type: Date
},
ip: {
type: String
},
user_agent: {
ua: {
type: String,
default: null
},
browser: {
name: {
type: String,
default: null
},
version: {
type: String,
default: null
},
major: {
type: String,
default: null
}
},
engine: {
version: {
type: String,
default: null
},
name: {
type: String,
default: null
}
},
os: {
name: {
type: String,
default: null
},
version: {
type: String,
default: null
}
},
device: {
model: {
type: String,
default: null
},
type: {
type: String,
default: null
},
vendor: {
type: String,
default: null
}
},
cpu: {
architecture: {
type: String,
default: null
}
}
}
},
login_histories: [{type: Schema.Types.ObjectId, ref: ‘user_login_history’}],
companies: [{type: Schema.Types.ObjectId, ref: ‘companies’}],
deleted: {
type: Boolean,
default: false
},
deleted_on: {
type: Date
},
delete_request: {
requested: {
type: Boolean
},
request_date: {
type: Date
},
request_ip: {
type: String
},
mail_sent: {
type: Boolean
},
processing_date: {
type: Date
}
},
meta: {
total_companies: {
type: Number,
default: 0
}
},
legal_policy: {
date: {
type: Date
},
ip: {
type: String,
default: null
},
user_agent: {
type: String,
default: null
},
type: {
type: String,
default: null
},
event: {
type: String,
default: null
}
},
preferences: {
mail_notification: {
on_change_password: {
type: Boolean,
default: true
},
on_profile_update: {
type: Boolean,
default: true
},
on_security_info_changed: {
type: Boolean,
default: true
},
on_company_create: {
type: Boolean,
default: true
}
}
},
plan: {
name: {
type: String,
default: ‘free’,
enum: [‘free’, ‘pro’]
},
total_companies_monthly: {
type: Number
},
total_customers_monthly: {
type: Number
},
total_products_monthly: {
type: Number
},
total_invoice_monthly: {
type: Number
},
history: [{
created: {
type: Date
},
name: {
type: String
},
log: {
type: String
},
paid_amount: {
type: Number
},
transaction_unique_id: {
type: String
}
}]
}
};

var collectionName = ‘users’;

var UserSchema = mongoose.Schema(schema, {
minimize: false,
toObject: {
virtuals: true,
transform: function (doc, ret, cb) {
delete ret._id;
delete ret.__v;
delete ret.id;
}
},
toJSON: {virtuals: true}, timestamps: {createdAt: ‘created_at’}
});

Changing File Permissions in cPanel

Permissions can be very important when it comes to hosting your website. Permissions can allow our server computer to write and edit your files. Along with that, some files need to be protected from writing and editing, as a security measure. You can change your file permissions in many ways.

Step 1: Open your File Manager and navigate to the file or folder that you need to change.

Step 2: Click on the name of the file or folder.

Step 3: Click on the Change Permissions link in the top menu of the File Manager page.

Step 4: Click on as many check boxes as you require to create the right permission. The permission numbers underneath the check boxes will update automatically.

Step 5: Click on the Change Permissions button when you are ready. The new permission level is saved and the display updated to show the modified file.

Setting up PHP, MySQL, phpmyadmin on mac sierra

Mac OS Sierra comes with PHP, MySQL pre installed isn’t it cool? There are two-label root directory, one is called system label and another is user label. The default system label root is “/Library/WebServer/Documents”. The other user label root is missing by default. In this article we’re going to work with user label root.

PHP installation

Create folder named “Sites” at your root directory. (For those who are newbies) From terminal type “cd” and “sudo mkdir Sites”. To run this user label system make a configuration file under /etc/apache2/users/{your-username}.conf (here in the place of “your-username” type your currently logged in users username) and place the below code in it.

<Directory "/Users/username/Sites/">
AllowOverride All
Options Indexes MultiViews FollowSymLinks
Require all granted
</Directory>

 

permission this file should be “-rw- r– r– 1 root” if not, run this command “sudo chmod 644 {your-username}.conf”

Next open the “/etc/apache2/httpd.conf” file to active some module

✓ LoadModule authz_core_module libexec/apache2/mod_authz_core.so
✓ LoadModule authz_host_module libexec/apache2/mod_authz_host.so
✓ LoadModule userdir_module libexec/apache2/mod_userdir.so
✓ LoadModule include_module libexec/apache2/mod_include.so
✓ LoadModule rewrite_module libexec/apache2/mod_rewrite.so
✓ LoadModule php5_module libexec/apache2/libphp5.so
✓ Include /private/etc/apache2/extra/httpd-userdir.conf

Then open another apache configuration file at “/etc/apache2/extra/httpd-userdir.conf “ and active module

✓ Include /private/etc/apache2/users/*.conf

Save and restart apache “sudo apachectl restart”

If your are going the web serving document root at “/Library/WebServer/Documents”, its good idea to allow any .htaccess file used to override the default settings. This can be done by editing the “/etc/apache2/httpd.conf” file “AllowOverride All”. Also uncomment the below module

✓ LoadModule rewrite_module libexec/apache2/mod_rewrite.so

To test php running write a php file under /Library/WebServer/Documents and name it according your wish and run through browser “localhost/{your-file- name.php}”

MySQL installation

Download MySQL from MySQL’s native website and install it manually.
The first time after installations a dialog box will popup showing a temporary password, save that carefully for future use. Stop MySQL and start in safe mood and change the given password to yours by running these below commands.

✓ sudo /usr/local/mysql/support-files/mysql.server stop
✓ sudo mysqld_safe — skip-grant- tables
✓ mysql -u root
✓ FLUSH PRIVILEGES;
✓ ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘MyNewPass’;
✓ sudo /usr/local/mysql/support-files/mysql.server start

You may be encountering the problem/error “ERROR! MySQL server PID file could not be found!”.

The problem is because the MySQL pid file isn’t in the MySQL configuration file. The default configuration sample file directory is “/usr/local/mysql/support-files/my-default.cnf”

Create a MySQL configuration file copy and pasting from “my-default.cnf tomy.cnf” And the PID file is under the directory “/usr/local/mysql/data/{your-pc-name}.pid”. At the bottom of configuration file write the MySQL pid path like “pid-file = /usr/local/var/mysql/{username}.pid”. look for running MySQL using command “ps -A | grep MySQL” and kill it “sudo kill -15 pidno” if any.
start MySQL “/usr/local/mysql/bin/mysql -v -uroot -p” here you will be promoted for password. Type the temporary password given/shown. First change the password “ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘MyNewPass’;”

To work with MySQL through terminal “/usr/local/mysql/bin/mysql -u root –p”

PHPMYADMIN

Download phpmyadmin, from your download directory rename it phpmyadmin and put it under (you created earlier) Sites folder Make a directory under phpmyadmin and name it config “Sudo mkdir ~/Sites/phpmyadmin/config”

Change the permission “chmod o+w ~/Sites/phpmyadmin/config”

Browse http://localhost/~{your-username}/phpmyadmin/setup/

Click on “new server” and then on Authentication tab fill the “password for config auth” with your desired password. Click save and then save. move the file under the config directory to direct phpmyadmin folder (one level up) and remove the config directory.

Browse http://localhost/~username/phpmyadmin/

Adding Custom Validation Rules in Valitron

Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies. Valitron uses simple, straightforward validation methods with a focus on readable and concise syntax. Valitron is the simple and pragmatic validation library we’ve been looking for.

Adding Custom Validation Rules :

To add your own validation rule, use the addInstanceRule method with a rule name, a custom callback or closure, and a error message to display in case of an error. The callback provided should return boolean true or false.

such as :

$validation->addInstanceRule(‘functionName’, function () {
return false;
});

$validation->rule(‘functionName’, ‘fieldName’)->message(‘Error Message’);

 

We can also use the following structure :

if (condition) {

$validation->addInstanceRule(‘functionName’, function () {
return false;
});

$validation->rule(‘functionName’, ‘fieldName’)->message(‘Error Message’);

}