SOLID Principles in PHP

SOLID is an acronym for five design principles intended to make software designs more understandable, flexible, and maintainable. The five principles are: Single responsibility principle, Open/closed principle, Liskov substitution principle, Interface segregation principle, and Dependency inversion principle. It is designed and developed by Robert C. Martin.

The single responsibility principle states that a class should have only one reason to change. The open/closed principle states that classes should be open for extension but closed for modification. The Liskov substitution principle states that any instance of a parent class should be replaceable by its subclasses without altering the correctness of the program. The interface segregation principle states that clients should not be forced to depend on methods they do not use. The dependency inversion principle states that high-level modules should not depend on low-level modules, but instead both should depend on abstractions. Let’s see all of this in detail

The SOLID principles help software engineers create software designs that are more understandable, flexible, and maintainable. By adhering to these principles, software engineers can create code that is easier to debug, extend, and maintain. The single responsibility principle, for example, helps engineers create code that is more modular, meaning that it can be changed without affecting the rest of the code. The open/closed principle helps engineers create code that can be easily extended without needing to modify the existing code. The Liskov substitution principle helps engineers refactor code while still ensuring that the program remains correct. The interface segregation principle helps engineers create code that is more loosely coupled, meaning that it is easier to make changes without impacting other parts of the code. Finally, the dependency inversion principle helps engineers create code that is more maintainable by ensuring that high-level modules do not depend on low-level modules.

Single Responsibility Principle

The single responsibility principle states that a class should have only one reason to change. This principle encourages code that is more modular, meaning that it can be changed without affecting the rest of the code.

For example, in PHP, a class might have methods for retrieving data from a database, formatting it for display, and displaying it to the user. This class violates the single responsibility principle, since it has three separate responsibilities (retrieving data from the database, formatting the data, and displaying it to the user).

A better approach would be to have separate classes for each responsibility. For example, one class could be responsible for retrieving data from the database, another for formatting the data, and a third for displaying the data to the user. This approach would make the code more modular, meaning that it could be more easily changed and maintained.

Here is an example of code that does not follow the single responsibility principle:

<?php

class DataHandler {
    public function getData() {
        // code to retrieve data from the database
    }
    
    public function formatData($data) {
        // code to format the data
    }
    
    public function displayData($data) {
        // code to display the data to the user
    }
}

$handler = new DataHandler();
$data = $handler->getData();
$data = $handler->formatData($data);
$handler->displayData($data);

Here is an example of code in PHP that follows the single responsibility principle:

<?php

class Database {
    public function getData() {
        // code to retrieve data from the database
    }
}

class Formatter {
    public function formatData($data) {
        // code to format the data
    }
}

class Display {
    public function displayData($data) {
        // code to display the data to the user
    }
}

$database = new Database();
$data = $database->getData();

$formatter = new Formatter();
$data = $formatter->formatData($data);

$display = new Display();
$display->displayData($data);

Open/closed Principle

The open/closed principle states that classes should be open for extension but closed for modification. This principle encourages code that is more reusable and can be easily extended without needing to modify the existing code.

For example, in PHP, a class might have a method for calculating the total of a purchase. This method could be modified to include additional discounts or taxes. However, this violates the open/closed principle, since the existing code must be changed in order to add additional discounts or taxes.

A better approach would be to have a separate class that is responsible for calculating discounts or taxes. This class can then be extended to add additional discounts or taxes without needing to change the existing code.

For example:

<?php

class Order {
    public function calculateTotal() {
        // code to calculate total
    }
}

class DiscountCalculator {
    public function calculateDiscount($total) {
        // code to calculate discount
    }
}

class TaxCalculator {
    public function calculateTax($total) {
        // code to calculate tax
    }
}

$order = new Order();
$total = $order->calculateTotal();

Here is another example of code in PHP that follows the open/closed principle:

<?php

abstract class PaymentMethod {
    abstract public function processPayment($amount);
}

class CreditCard extends PaymentMethod {
    public function processPayment($amount) {
        // code to process payment with credit card
    }
}

class PayPal extends PaymentMethod {
    public function processPayment($amount) {
        // code to process payment with PayPal
    }
}

$paymentMethod = new CreditCard();
$paymentMethod->processPayment(100);

In this example, the abstract class PaymentMethod defines an abstract method processPayment(), which must be implemented by any class that extends it. The CreditCard and PayPal classes extend PaymentMethod and implement the processPayment() method. This allows the code to be easily extended to include additional payment methods without needing to modify the existing code.

Liskov substitution principle

The Liskov substitution principle states that any instance of a parent class should be replaceable by its subclasses without altering the correctness of the program. This principle encourages code that is more modular, meaning that it can be changed without affecting the rest of the code.

For example, a parent class might define a method for calculating the area of a shape. A subclass might override this method to calculate the area of a triangle, but it should still produce the same result as the parent class method. This ensures that code that relies on the parent class can still work correctly when using the subclass.

Here is an example of code in PHP that follows the Liskov substitution principle:

<?php

abstract class Shape {
    abstract public function calculateArea();
}

class Circle extends Shape {
    private $radius;
    
    public function __construct($radius) {
        $this->radius = $radius;
    }
    
    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }
}

class Square extends Shape {
    private $side;
    
    public function __construct($side) {
        $this->side = $side;
    }
    
    public function calculateArea() {
        return pow($this->side, 2);
    }
}

function calculateTotalArea(Shape $shape) {
    return $shape->calculateArea();
}

$circle = new Circle(2);
$area = calculateTotalArea($circle); // 12.566370614359

Interface segregation principle

The interface segregation principle states that clients should not be forced to depend on methods they do not use. This principle encourages code that is more loosely coupled, meaning that it is easier to make changes without impacting other parts of the code.

For example, in PHP, a class might have several methods for retrieving data from a database. However, if a client only requires one of these methods, it should not be forced to depend on the other methods.

A better approach would be to have separate interfaces for each responsibility. For example, one interface could be responsible for retrieving data from the database, another for formatting the data, and a third for displaying the data to the user. This approach would make the code more loosely coupled, meaning that it could be more easily changed and maintained.

For example:

<?php

interface DatabaseRetriever {
    public function getData($query);
}

interface DataFormatter {
    public function formatData($data);
}

interface DataDisplayer {
    public function displayData($data);
}

class DatabaseRetrieverImpl implements DatabaseRetriever {
    public function getData($query) {
        // code to retrieve data from the database
    }
}

class FormatterImpl implements DataFormatter {
    public function formatData($data) {
        // code to format the data
    }
}

class DisplayImpl implements DataDisplayer {
    public function displayData($data) {
        // code to display the data to the user
    }
}

In this example, there are three separate interfaces: DatabaseRetriever, DataFormatter, and DataDisplayer. Each interface defines one responsibility, and any class that implements one of these interfaces is only required to implement that responsibility. This ensures that classes can be easily extended to include additional responsibilities without needing to modify the existing code. For example, if a new requirement arises to format the data before displaying it, the FormatterImpl class can be extended to include this functionality without needing to modify the DatabaseRetrieverImpl or DisplayImpl classes.

Dependency inversion principle

The dependency inversion principle states that high-level modules should not depend on low-level modules, but instead both should depend on abstractions. This principle encourages code that is more maintainable by ensuring that high-level modules do not depend on low-level modules.

For example, in PHP, a high-level module might depend on a low-level module to retrieve data from a database. This violates the dependency inversion principle, since the high-level module is now dependent on the low-level module.

A better approach would be to have an abstraction that is responsible for retrieving data from the database. This abstraction can then be implemented by a low-level module, and the high-level module can depend on the abstraction instead of the low-level module. This approach would make the code more maintainable, since the high-level module does not need to be changed if the implementation of the low-level module changes.

For example:

<?php

interface DatabaseInterface {
    public function getData($query);
}

class Database implements DatabaseInterface {
    public function getData($query) {
        // code to retrieve data from the database
    }
}

class HighLevelModule {
    private $database;
    
    public function __construct(DatabaseInterface $database) {
        $this->database = $database;
    }
    
    public function getData($query) {
        return $this->database->getData($query);
    }
}

$database = new Database();
$highLevelModule = new HighLevelModule($database);
$data = $highLevelModule->getData('SELECT * FROM table');

Here is a more realistic example of code in PHP that follows the dependency inversion principle:

<?php

interface LoggerInterface {
    public function log($message);
}

class FileLogger implements LoggerInterface {
    public function log($message) {
        // code to write message to log file
    }
}

class DatabaseLogger implements LoggerInterface {
    public function log($message) {
        // code to write message to database
    }
}

class User {
    private $logger;
    
    public function __construct(LoggerInterface $logger) {
        $this->logger = $logger;
    }
    
    public function log($message) {
        $this->logger->log($message);
    }
}

In this example, the User class depends on an abstraction (the LoggerInterface) instead of a concrete class (the FileLogger or DatabaseLogger classes). This ensures that the User class does not need to be changed if the implementation of the logger classes changes. For example, if a new requirement arises to log messages to a different source, the FileLogger or DatabaseLogger classes can be replaced with a different class that implements the LoggerInterface interface, and the User class does not need to be changed.

Repository pattern in PHP and its use cases

The Repository Pattern is a design pattern that provides a centralized location for data access and management in an application. It acts as an intermediary between the data layer (such as a database) and the application layer. The Repository Pattern is used to separate the application’s data access logic from the rest of the application.

Here is an example of the Repository Pattern in PHP:

<?php

interface RepositoryInterface {
    public function getAll();
    public function getById($id);
    public function create($data);
    public function update($id, $data);
    public function delete($id);
}

class UserRepository implements RepositoryInterface {
    private $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    public function getAll() {
        $stmt = $this->db->prepare("SELECT * FROM users");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }

    public function getById($id) {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id=?");
        $stmt->execute([$id]);
        return $stmt->fetch(PDO::FETCH_OBJ);
    }

    public function create($data) {
        $stmt = $this->db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
        return $stmt->execute([$data['name'], $data['email']]);
    }

    public function update($id, $data) {
        $stmt = $this->db->prepare("UPDATE users SET name=?, email=? WHERE id=?");
        return $stmt->execute([$data['name'], $data['email'], $id]);
    }

    public function delete($id) {
        $stmt = $this->db->prepare("DELETE FROM users WHERE id=?");
        return $stmt->execute([$id]);
    }
}

In this example, the RepositoryInterface defines the methods that a repository must implement. The UserRepository class implements the RepositoryInterface and provides the actual implementation for the methods. The UserRepository class uses the PDO class to access the database.

With the Repository Pattern, the application can access the data through the repository and the repository takes care of the actual data access logic. This helps to keep the data access logic separate from the rest of the application and makes it easier to maintain and update the application.

The Repository Pattern has several use cases, including:

  1. Decoupling the data access logic from the rest of the application: By using the Repository Pattern, the data access logic can be separated from the rest of the application. This makes it easier to change the data access logic without affecting the rest of the application.
  2. Centralizing data access: The Repository Pattern provides a centralized location for data access and management. This makes it easier to manage the data access logic and to maintain a consistent way of accessing data throughout the application.
  3. Enhancing testability: By using the Repository Pattern, it is easier to write unit tests for the data access logic. The tests can be written against the repository interface, which allows for easy mocking of the data access layer.
  4. Improving security: The Repository Pattern can help to improve the security of the application by centralizing the data access logic and enforcing a consistent way of accessing data. This makes it easier to implement security measures, such as input validation and output sanitization, in a single location.
  5. Supporting multiple data sources: The Repository Pattern can be used to support multiple data sources. By creating a separate repository for each data source, the application can access each data source in a consistent way.
  6. Facilitating code reuse: The Repository Pattern makes it easier to reuse the data access logic across multiple parts of the application. This can lead to more consistent and efficient data access, as well as faster development times.

Overall, the Repository Pattern is a useful tool for organizing the data access logic in an application and making it easier to maintain and update.

Here is an example of how the Repository Pattern can enhance testability in PHP:

<?php

interface UserRepositoryInterface {
    public function getByEmailAndPassword($email, $password);
}

class UserRepository implements UserRepositoryInterface {
    private $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    public function getByEmailAndPassword($email, $password) {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE email=? AND password=?");
        $stmt->execute([$email, hash('sha256', $password)]);
        return $stmt->fetch(PDO::FETCH_OBJ);
    }
}

class UserService {
    private $userRepository;

    public function __construct(UserRepositoryInterface $userRepository) {
        $this->userRepository = $userRepository;
    }

    public function login($email, $password) {
        $user = $this->userRepository->getByEmailAndPassword($email, $password);
        if (!$user) {
            throw new Exception("Invalid email or password");
        }
        return $user;
    }
}

In this example, the UserRepository implements the UserRepositoryInterface and provides the implementation for the getByEmailAndPassword method, which retrieves a user from the database based on the email and password. The UserService class depends on the UserRepositoryInterface and uses the repository to access the data. The login method in the UserService class uses the repository to retrieve the user based on the email and password, and throws an exception if the user is not found.

This design makes it easy to write unit tests for the UserService class, as it can be tested in isolation from the data access layer. You can mock the UserRepository and configure it to return specific values for the getByEmailAndPassword method, which makes the tests more reliable and easier to write.

Here’s an example of a unit test for the login method in the UserService class:

<?php

use PHPUnit\Framework\TestCase;

class UserServiceTest extends TestCase {
    public function testLoginSuccess() {
        $email = "test@example.com";
        $password = "password";
        $user = (object) [
            "id" => 1,
            "email" => $email,
            "password" => hash('sha256', $password),
        ];

        $userRepositoryMock = $this->createMock(UserRepositoryInterface::class);
        $userRepositoryMock->expects($this->once())
            ->method('getByEmailAndPassword')
            ->with($this->equalTo($email), $this->equalTo($password))
            ->willReturn($user);

        $userService = new UserService($userRepositoryMock);
        $result = $userService->login($email, $password);

        $this->assertEquals($user, $result);
    }

    public function testLoginFail() {
        $email = "test@example.com";
        $password = "password";

        $userRepositoryMock = $this->createMock(UserRepositoryInterface::class);
        $userRepositoryMock->expects($this->once())
            ->method('getByEmailAndPassword')
            ->with($this->equalTo($email), $this->equalTo($password))
            ->willReturn(null);

        $userService = new UserService($userRepositoryMock);

        $this->expectException(Exception::class);
        $this->expectExceptionMessage("Invalid email or password");
        $userService->login($email, $password);
    }
}

In this example, the test class extends the PHPUnit\Framework\TestCase class, which provides a testing framework for writing unit tests in PHP. The testLoginSuccess method creates a mock object for the UserRepository using the createMock method, and configures it to return a specific user when the getByEmailAndPassword method is called. The UserService is instantiated with the mock repository, and the login method is called with the email and password. The result is then compared to the expected user to ensure that the method is working as expected.

The testLoginFail method is similar, but it configures the mock repository to return null, which represents an invalid email and password. The test then expects an exception to be thrown with a specific message, which is checked to ensure that the exception is thrown correctly.

These tests ensure that the UserService class is working correctly, and that it will behave correctly in the event of an invalid login attempt. The tests are also isolated from the actual data access layer, which makes them more reliable and easier to maintain over time.

Setup Docker on your PHP, MySql and Ngnix web application

Docker is a powerful tool that allows developers to easily create and manage isolated environments for their applications. In this guide, we will walk through the process of setting up a Docker environment for PHP development that includes MySQL, Composer, and Nginx.

Step 1: Install Docker and Docker Compose

The first step is to install Docker and Docker Compose on your machine. You can download the Docker Desktop for Mac or Windows, or for Linux you can follow the instructions for your specific distribution. Here are the instruction for install it on linux ubuntu

To install Docker:

  1. Update the system: sudo apt update
  2. Install dependencies: sudo apt install apt-transport-https ca-certificates curl software-properties-common
  3. Add Docker GPG key: curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
  4. Add Docker repository: sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
  5. Update package index: sudo apt update
  6. Install Docker: sudo apt install docker-ce

To install Docker Compose:

  1. Download the binary: sudo curl -L "https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  2. Apply executable permissions: sudo chmod +x /usr/local/bin/docker-compose
  3. Verify the installation: docker-compose --version

Step 2: Create a new directory for your project

Create a new directory for your project and navigate into it. This will be the root of your project and where all of your code and configuration files will be stored.

Step 3: Create a Dockerfile

Create a new file called “Dockerfile” in your project’s root directory. This file will contain the instructions for building your Docker image.

Here is an example of a basic Dockerfile for PHP development:

FROM php:7.4-fpm

RUN apt-get update && apt-get install -y \
    libpq-dev \
    libzip-dev \
    zip \
    unzip

RUN docker-php-ext-install pdo_mysql \
    && docker-php-ext-configure zip --with-libzip \
    && docker-php-ext-install zip

COPY . /var/www/html

WORKDIR /var/www/html

CMD ["php-fpm"]

This Dockerfile starts from the official PHP 7.4 FPM image, installs the necessary dependencies for using PDO with MySQL and the Zip extension, copies the contents of the current directory to the webroot, and sets the working directory to the webroot.

  1. FROM php:7.4-fpm specifies the base image to be used for building the Docker image. In this case, it’s using the PHP 7.4 FPM (FastCGI Process Manager) image from the official PHP Docker repository.
  2. RUN apt-get update && apt-get install -y updates the package list and installs the dependencies listed after it:
    • libpq-dev
    • libzip-dev
    • zip
    • unzip
  3. RUN docker-php-ext-install pdo_mysql installs the PDO (PHP Data Objects) extension for MySQL.
    • docker-php-ext-configure zip --with-libzip configures the zip extension to use libzip.
    • docker-php-ext-install zip installs the zip extension.
  4. COPY . /var/www/html copies all the files in the current directory to the /var/www/html directory in the Docker image.
  5. WORKDIR /var/www/html sets the working directory to /var/www/html, where the application files will be located.
  6. CMD ["php-fpm"] specifies the command to run when the Docker image is started. In this case, it’s running the php-fpm service.

Step 4: Create a docker-compose.yml file

Create a new file called “docker-compose.yml” in your project’s root directory. This file will define the services that make up your application and how they are connected.

Here is an example of a basic docker-compose.yml file for PHP development:

version: '3'
services:
  web:
    build: .
    ports:
      - "9000:9000"
    volumes:
      - .:/var/www/html
  db:
    image: mysql:5.7
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: mydb
      MYSQL_USER: myuser
      MYSQL_PASSWORD: mypassword
  nginx:
    image: nginx:latest
    ports:
      - "80:80"
    volumes:
      - .:/var/www/html
      - ./nginx/default.conf:/etc/nginx/conf.d/default.conf

The file docker-compose.yml is used to define and run multi-container Docker applications with Docker Compose. The content in the file describes the services needed to run the application and how they should be configured.

  1. version: '3' specifies the version of the Docker Compose file format used. In this case, it’s using version 3.
  2. services: section defines the services needed for the application:
    • web: section describes the service that runs the web application.
      • build: . specifies that the Docker image should be built using the Dockerfile in the current directory.
      • ports: maps the host’s port 9000 to the container’s port 9000, allowing external access to the web service.
      • volumes: mounts the current directory to the /var/www/html directory in the container, allowing changes to the code to take effect immediately.
    • db: section describes the service that runs the database.
      • image: mysql:5.7 specifies the MySQL 5.7 image to be used for the database service.
      • ports: maps the host’s port 3306 to the container’s port 3306, allowing external access to the database.
      • environment: sets the environment variables for the database service, including the root password, database name, user, and user password.
    • nginx: section describes the service that runs the web server.
      • image: nginx:latest specifies the latest version of the Nginx image to be used for the web server service.
      • ports: maps the host’s port 80 to the container’s port 80, allowing external access to the web server.
      • volumes: mounts the current directory to the /var/www/html directory in the container and the nginx/default.conf file to the /etc/nginx/conf.d/default.conf file in the container, allowing changes to the configuration to take effect immediately.

This file defines three services: web, db, and nginx. The web service uses the Dockerfile in the current directory, maps port 9000 to the host, and mounts the current directory as a volume. The db service uses the official MySQL 5.7 image, maps port 3306 to the host, and sets the necessary environment variables for the root password, database name, user, and password. The nginx service uses the official Nginx image, maps port 80 to the host, and mounts the current

Introduction to PHP: The Language of the web | PHP Beginner to Advance

After working with PHP for 14 years, I was thinking about how the new developers starting with PHP who has little to no knowledge of PHP. So I thought to write a series of blog posts that will help newcomers. So let’s dive in.

PHP, or Hypertext Preprocessor, is a popular server-side programming language that is widely used for building dynamic websites and web applications. The language was first created in 1995 by Rasmus Lerdorf and has since grown to become one of the most widely-used programming languages on the web.

PHP is an open-source language, meaning that it is free to use and distribute. It is also easy to learn, making it a popular choice for beginners and experienced developers alike. The language is particularly well-suited for web development, as it allows for the creation of dynamic pages that can interact with databases and other web services.

The basic syntax of PHP is similar to other languages such as C and Perl. It uses a combination of HTML, CSS, and JavaScript to create dynamic web pages. PHP code is executed on the server and the result is returned to the client as HTML, which is then displayed in the user’s web browser.

One of the benefits of using PHP is that it can be easily integrated with other technologies such as databases (e.g MySQL) and web frameworks (e.g Laravel, CodeIgniter, Symfony) to create powerful web applications.

To get started with PHP, you’ll need a web server (e.g Apache, Nginx) and a text editor to write your code. There are also a number of development environments available, such as XAMPP and WAMP, that provide an easy way to set up a local web server for testing and development.

Once you’ve set up your environment, you can start experimenting with PHP by creating simple scripts and experimenting with the language’s built-in functions and control structures. You can also refer to resources such as PHP documentation and online tutorials to learn more about the language.

Further Reading:

These are some of the books that can be helpful in learning PHP. Additionally, there are numerous tutorials, videos, and online courses available that can help you get started with PHP.

In conclusion, PHP is a powerful, flexible, and easy-to-learn programming language that is well-suited for web development. Whether you’re a beginner or an experienced developer, there are plenty of resources available to help you learn and master the language.

Here are the other parts of the series

  • Introduction to PHP: The Language of the web | PHP Beginner to Advance
  • More to Come…

Error : 1067 the process terminated unexpectedly in mysql wamp

Recently I encountered a problem with MySQL, It was showing an error “Error : 1067 the process terminated unexpectedly” when I tried to start the service in services.msc

So I googled it but didn’t found the perfect solution. I will show how can you debug the issue. First look for file my.ini which can be found in “C:\wamp\bin\mysql\mysql5.6.17” , open that file on look for “log-error”, this will show you the path where error log is stored. In my case it is, “c:/wamp/logs/mysql.log”.

Open the log file and look for last error you got, you should be today’s date when you tried to start the wampmysqld from services. At this stage, you will get error and understand what it say. In my case it is,

InnoDB: Attempted to open a previously opened tablespace. Previous tablespace kmk/players uses space ID: 58 at filepath: .\kmk\players.ibd. Cannot open tablespace ocean/acos which uses space ID: 58 at filepath: .\ocean\acos.ibd
InnoDB: Error: could not open single-table tablespace file .\ocean\acos.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.

Looking at error, it seems that there is some problem with “kmk\players.ibd” , here kmk it one of the my database. The folders for all databases are in “C:\wamp\bin\mysql\mysql5.6.17\data”. To fix I moved kmk folder to some other place. After this, wampmysqld in services.msc is getting started without any error.

That fixed my error.

Share your experience and error in log file in comment section. This will also prevent other from reinstalling wamp server.

Thanks

ORM – Object Relational Mapping in PHP

ORM- Object Relational Mapping is a tool which allows database row to refer as object in PHP programming.  What Wikipedia says about ORM is:

Object-relational mapping (ORM, O/RM, and O/R mapping) in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language.

(Object-Relational Mapping) is a tool that allows you query database table and manipulate data from a database using an object paradigm (Object Oriented).

ORM is library which helps you in query the data using functions so that PHP developer do not have to write database query manually. It uses model objects to get the database table’s data.

Let understand this with simple example code. You have a book class and you want to fetch the books whose author is ‘Peter’. To get list of books, you may write similar kind of code as follow:

$book_list = new List();
$sql = "SELECT * FROM books WHERE author = 'Peter'";
$result = mysql_query($sql); // I over simplify ...
while ($row = mysql_fetch_assoc($result)) {
     $book = new Book();
     $book.setAuthor($row.get('author');
     $book_list.add($book);
}

Above code using ORM can be written as simple as follow:

$book_list = Book.query(author="Peter");

All the mechanical part is taken care by the ORM. You write almost no query  retrieving the data from table/s.

Advantages

ORM saves time because:

  1. It uses DRY concept. You write your data model in only one place, it’s easier to update, maintain and reuse the code.
  2. A lot of stuff for database manipulation is done automatically, maintaining relation and fetching data is also some times automatically.
  3. It forces you to write code in MVC (Model-View-Controller) structure, so in the end your application code will be cleaner.
  4. You don’t have to write formed SQL statements, complex relational query are handled by ORM
  5. Sanitizing, using prepared statements or transactions are as easy as calling a method.

ORM is flexible to use:

  1. It fits in your natural way of coding.
  2. It abstracts the DB system, so you can change it whenever you want.
  3. The model is weakly bound to the rest of the app, so you can change it or use it anywhere else.
  4. It let you use OOP goodness like data inheritance without head ache.

Disadvantages

  1. You have to learn it, and they are not lightweight tools;
  2. You have to set it up. Same problem.
  3. Performances are ok for usual queries, but a SQL master will always do better with his little hands for the big dirty works.
  4. It abstracts the DB. While it’s ok if you know what’s happening behind the scene, it’s a trap for the novice that can write very greedy statements, like a heavy hit in a “for” loop.

Available ORM in PHP are Propel and Doctrine. You can use any one.

Thanks for reading the article. I have taken the help from stackoverflow to write on ORM. Thanks to stackoverflow.

Please feel free to comment if you have any confusion.

OpenCart – Simple Age Verification PopUp – VQMOD Extension

Simple Age Verification PopUp OpenCart extension is nice plugin to verify the age before entering the site. This is helpful for adult site, smoking or alcohol sites to verify the age before visitor enters your website.

Simple Age Verification Popup plugin opens popup in cool lightbox with image and check box with it. See the below screenshop of popup.

Are-you-18+

 

This is VQMOD extension of OpenCart. VQMOD helps in not overwriting the core files of OpenCart.

You can find more info on VQMOD and Download here.

Steps to install this Extension:

  1. Install VQMOD, if it is not installed.
  2. Download the zip file, extract somewhere on your computer. 
  3. From extracted file, upload the the files/folder under “upload” folder to server using FTP, in root folder (where admin,catalog,system folder are available) of OpenCart installation and its done you do not have to do anything else to make it work.

 

Click Here to Download OpenCart – Simple Age Verification PopUp – VQMOD Extension

OpenCart – Show Reward Points of Customer In Header – VQMOD Extension

Show Reward Point of Customer in Header plugin do exactly what it’s name implies. In OpenCart, After login as Customer to view reward point customer have to go to My Account > Your Reward Points. This Free extension / plugin of OpenCart show Rewards points in Header under Login info.

Here is the screenshot how it looks like on default theme.

show-reward-point-in-header

 

This is VQMOD extension of OpenCart. No Core file is updated using VQMOD.

You can download this plugin from here.

OpenCart – Auto Add Reward Points – VQMOD Extension

New OpenCart Extension, Auto Add Reward Points add product rewards points to customer immediately after purchase finished. Usually in OpenCart website admin have to add reward point to customer manually by clicking on link as show in below screenshot.

auto-add-reward-point

 

Using Auto add reward point extension / plugin for OpenCart do not require to add rewards point manually. It does automatically for admin. It helps admin in reducing tedious task of adding rewards point for every product purchased.

This is VQMOD extension so you require VQMOD to be installed on OpenCart website. You can find the information of installing VQMOD here.

Steps to install extension:

It is really easy to install this plugin.

  1. Install VQMOD, if it is not installed.
  2. Download the zip file, extract somewhere on your computer. 
  3. From extracted file, upload the the files/folder under “upload” folder to server using FTP, in root folder (where admin,catalog,system folder are available) of Opencart installation and its done you do not have to do anything else to make it work.

Click Here to Download OpenCart – Auto Add Reward Points – VQMOD Extension

PHP – Securing your Web Application : More information and Summary

This is a last article in this series.

More Information

The following resources can help you expand on this brief introduction:

Security Recap and Summary

Because security is such an important issue, we want to reiterate the main points of this series of tutorials as well as add a few additional tips:

  • Filter input to be sure that all data you receive from remote sources is the data you expect. Remember, the stricter your filtering logic, the safer your application.
  • Escape output in a context-aware manner to be sure that your data isn’t misinterpreted by a remote system.
  • Always initialize your variables. This is especially important when the register_globals directive is enabled.
  • Disable register_globals, magic_quotes_gpc, and allow_url_fopen. See http://www.php.net for details on these directives.
  • Whenever you construct a filename, check the components with basename() and realpath().
  • Store includes outside of the document root. It is better to not name your included files with the .inc extension. Name them with a .php extension, or some other less obvious extension.
  • Always call session_regenerate_id() whenever a user’s privilege level changes.
  • Whenever you construct a filename from a user-supplied component, check the components with basename() and realpath().
  • Don’t create a file and then change its permissions. Instead, set umask() so that the file is created with the correct permissions.
  • Don’t use user-supplied data with eval(), preg_replace() with the /e option, or any of the system commands— exec(), system(), popen(), passthru(), and the backtick (`) operator.

Here is the list of of Article in this Series:

Please share the article if you like let your friends learn PHP Security. Please comment any suggestion or queries.

 

Thanks Kevin Tatroe, Peter MacIntyre and Rasmus Lerdorf. Special Thanks to O’Relly.