Symfony – Create a service – the right way

Always create service interface for your service. This way you will have better structured code and phpunit testing will be real pleasure.
Also use dependency injection for your repositories in the service.

Service Interface Example

interface UserServiceInterface{
  public function getUsername();
  public function viewAll();
}

Service Example

class UserService implements UserServiceInterface
{

  private $entityManager;
  private $userRepository;

  public function __construct(EntityManager $entityManager, UserRepository $userRepository)
  {
    $this->entityManager = $entityManager;
    $this->userRepository = $userRepository;
  }

  public function viewAll()
  {
    return $this->userRepository->findAll();
  }
}

Repository Example

class UserRepository extends \Doctrine\ORM\EntityRepository
{
  public function __construct(EntityManager $em, Mapping\ClassMetadata $metadata = null)
  {
    parent::__construct(
      $em,
      $metadata == null ?
      new Mapping\ClassMetadata(User::class) :
      $metadata
    );
  }
}

Symfony Security Authorization

There are several way to make authorization on your site with Symfony.
First is in your security.yml on the same level as firewalls tag:

access_control:
        - { path: ^/admin, roles: ROLE_USER }

This will block all users that don’t have ‘ROLE_USER’ to admin page.

Second option is to use Controller. Inside Method insert:

        if(!$this->get('security.authorization_checker')->isGranted('ROLE_ADMIN')){
            throw $this->createAccessDeniedException('GET OUT!');
        }

Or like this:

$this->denyAccessUnlessGranted('ROLE_ADMIN');

This will deny access to all users that don’t have ‘ROLE_ADMIN’ to this method.

You can also use annotations:

/**
* @Security("is_granted('ROLE_ADMIN')")
*/

Annotations also work if you add them to the Class. So they will block all users that don’t have ‘ROLE_ADMIN’ to this class.

Continue reading “Symfony Security Authorization” »

Symfony Security Authentication

Create Entity named User

< ?php

namespace AppBundle\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", unique=true)
     */
    private $email;

    /**
     * @ORM\Column(type="string")
     */
    private $password;

    private $plainPassword;

    public function getUsername()
    {
        return $this->email;
    }

    public function getRoles()
    {
        return ['ROLE_USER'];
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getSalt()
    {
    }

    public function eraseCredentials()
    {
        $this->plainPassword = null;
    }

    /**
     * @param mixed $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * @param mixed $password
     */
    public function setPassword($password)
    {
        $this->password = $password;
    }

    /**
     * @return mixed
     */
    public function getPlainPassword()
    {
        return $this->plainPassword;
    }

    /**
     * @param mixed $plainPassword
     */
    public function setPlainPassword($plainPassword)
    {
        $this->plainPassword = $plainPassword;
        //This should be here to set value for password to activate doctrine listeners
        $this->password = null;
    }



}

and generate migration:

#php bin/console doctrine:migrations:diff
#php bin/console doctrine:migrations:migrate

Continue reading “Symfony Security Authentication” »

PHP CURL Function Example

This function is populated with all needed data for curl to be executed

function get_curl($site_url){
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_URL, $site_url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
	curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');

	$headers = array();
	$headers[] = "Accept-Encoding: gzip, deflate, sdch";
	$headers[] = "Accept-Language: en-US,en;q=0.8";
	$headers[] = "Upgrade-Insecure-Requests: 1";
	$headers[] = "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.59 Safari/537.36";
	$headers[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
	$headers[] = "Referer: $site_url";
	//Set a cookie if needed (you can set other values)
	$headers[] = "Cookie: D_SID=185.196.133.50:u147oywWqvEJoD/GIlY10erXbeio1QIKGdi6Vo6/HVo; D_IID=0108BE8F-6C68-31CF-9B9D-4308308DB3A6; D_UID=5A4BCE68-9FD2-3A70-B1DF-376B7D77FD4B; D_ZID=248B7EFC-E23A-3F71-A675-764EA373AEC6; D_ZUID=4DFFC8BD-0AD9-3DE0-94AE-60A57D49736A; D_HID=07EDD9E4-1EDF-3EE3-9D52-B67B5952F6EC";
	$headers[] = "Connection: keep-alive";
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

	$result = curl_exec($ch);

	if (curl_error($ch)) {
		$output['status'] = '404';
		$output['msge'] = curl_error($ch);
	} else {
		$output['status'] = 'ok';
		$output['html'] = $result;
	}

	curl_close ($ch);
	return $output;
}

Send Array to API with POST

function send_curl(array $array)
    {

        $api = 'https://localhost/services/api';
        $action = 'test';
        $password = 'TestPass';

        $ch = curl_init($api);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(
            [
                'password' => $password ,
                'data' => $array,
                'action' => $action,
            ]
        ));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $serverOutput = curl_exec($ch);
        curl_close($ch);

        return $serverOutput;
    }

MySQL Foreign Keys

A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.

* If you want to use foreign key all your tables should be with InnoDB engine.

Foreign Key on create table

CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,
    PersonID int,
    PRIMARY KEY (OrderID),
    FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

Continue reading “MySQL Foreign Keys” »

Setup Linux Ubuntu For Web Development

Install Node.js

sudo apt-get install curl

curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -

sudo apt-get install -y nodejs

Install LAMP stack

sudo apt-get install apache2

sudo apt-get install php7.0 libapache2-mod-php7.0

sudo apt-get install mysql-server

sudo /etc/init.d/apache2 restart

Install phpmyadmin

sudo apt-get install phpmyadmin

sudo nano /etc/php/7.0/apache2/php.ini

Uncomment extension=msql.so

sudo /etc/init.d/apache2 restart
sudo nano /etc/apache2/apache2.conf 

At the bottom of the file write:

Include /etc/phpmyadmin/apache.conf

Save it and then:

sudo /etc/init.d/apache2 restart

Install Filezilla

sudo apt-get install filezilla

Install Gimp

sudo add-apt-repository ppa:otto-kesselgulasch/gimp

sudo apt-get update

sudo apt-get install gimp

Install Chrome

wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -

echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | sudo tee /etc/apt/sources.list.d/google-chrome.list

sudo apt-get update 
sudo apt-get install google-chrome-stable

Install PhpStorm

Download linux version from https://www.jetbrains.com/phpstorm/download/

sudo tar xf PhpStorm-*.tar.gz -C /opt/

cd /opt/PhpStorm-*/bin

./phpstorm.sh
License server: http://www.aku.vn/idea

Linux basic commands

pwd -> show the current working directory
ls -a -> show list of all files and folders (hidden also)
ls -l -> show list of all files and folders with their permissions

mkdir -> Make directory
rmdir -> Delete directory
rm -R -> Delete directory even if it is not empty

cd -> moves back to your home directory
cd .. -> moves back one directory
cd / -> moves to root directory of linux
cd ~ -> moves to home directory

touch file.txt -> create file
nano file.txt -> edit file with nano-editor
cat file.txt -> show the contents of a file
less file.txt -> show the contents of a file with scroll
mv file.txt new.txt -> rename filename
cp file.txt new.txt -> copy file
rm file.txt -> delete file
chmod -> is used to change the permissions of files or directories (example “chmod 754 myfile”)

which -> shows program or folder location
history -> show last 500 commands

ifconfig -> network info
iwconfig -> wireless info

top -> shows the top processes based on certain criterias like cpu usage or memory usage
df -> disk space

sudo apt-get install “program-name” -> install program
sudo apt-get remove “program-name” -> delete program
sudo apt-get update -> update all packages
sudo shutdown -h -> shutdown system (halt)
sudo shutdown -r -> restart system