Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday, August 21, 2014

Set up a Symfony2 dev environment in 10 minutes with Vagrant

Let's keep it simple. It is just a quick draft how can you set up a Symfony2 development environment in a few minutes.

I'll use Vagrant (you'll need version 1.5 at least) and my dev box to create the desired environment.

The box main components are: Ubuntu14.04, Nginx1.6, Php5.5Fpm, Xdebug, Composer, MySql5.5, NodeJs0.10.30, Redis and it has PhpMyAdmin, Webgrind and RedisCommander.

So the steps are:
  • Create the Vagrantfile
    # -*- mode: ruby -*-
    # vi: set ft=ruby :
    
    VAGRANTFILE_API_VERSION = "2"
    
    Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
      config.vm.box = "adammbalogh/lemp"
    
      config.vm.network "private_network", ip: "192.168.33.10"
      config.vm.synced_folder "app/", "/var/www/app/"
    
      config.vm.provider "virtualbox" do |vb|
        vb.customize ["modifyvm", :id, "--memory", "1512"]
        vb.customize ["modifyvm", :id, "--cpuexecutioncap", "85"]
      end
    end
    
    
  • mkdir app
  • vagrant up
  • vagrant ssh
  • cd /var/www/app
  • composer create-project symfony/framework-standard-edition . '~2.5'
  • nano app/AppKernel.php (and add these two methods)
    public function getCacheDir()
    {
        return '/tmp/symfony/cache/' . $this->environment;
    }
    
    public function getLogDir()
    {
        return '/tmp/symfony/log/' . $this->environment;
    }
    
  • nano web/app_dev.php (and delete these lines)
    if (isset($_SERVER['HTTP_CLIENT_IP'])
        || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
        || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1',$
    ) {
        header('HTTP/1.0 403 Forbidden');
        exit('You are not allowed to access this file. Check '.basename(__FIL$
    }
    
  • app/console cache:clear --env=dev (to test it)

Wednesday, July 9, 2014

Upstart

If you have ever have a problem with php forking, upstart will be your good friend.

What is upstart?
In short: service management daemon

"Upstart is an event-based replacement for the /sbin/init daemon which handles starting of tasks and services during boot, stopping them during shutdown and supervising them while the system is running."

Let's make it clear (from our perspective):
You can start any of your (php) scripts as a daemon (even with arguments) with a handy toolset: status / start / stop / restart

Config your job (e.g. a script)
Pretend that you have a my-awesome-app.php, which you want to start as daemon on every system boot. Your script can easily become fragile, so you also want to monitor it with a respawn mechanism.

First, you have to create an upstart config and place it in the /etc/init directory. In this case it will be this one: /etc/init/my-awesome-app.conf

# /etc/init/my-awesome-app.conf
description "daemonized awesome app"
version "1.0"
author "adammbalogh"

# restart my app on a crash
respawn
# stop restarting my app if it crashes more than 5 times in 30 sec
respawn limit 5 30

# start my script after nginx started
start on started nginx
# stop it on system shutdown
stop on runlevel S

# run as user and group
setuid www-data
setgid www-data

script
  exec php /home/user/public_html/my-awesome-app.php
end script

After you've created this conf file, just start your app with upstart: sudo start my-awesome-app.conf

Misc
You can also create pre or post scripts with a simple statement.

pre-start script
  exec touch /tmp/myapp.log
end script

If you want to use configuration variable you can do it too.

env BYE=goodbye
post-start script
  exec echo $BYE >> /tmp/myapp.log
end script

Finally, a useful cmd which lists all jobs and their states: initctl list

Monday, July 7, 2014

Web and Cli Debugging with PhpStorm, XDebug in Vagrant

We've a Vagrant box in a development environment and want to debug our application. Take a quick review of the two main ways, so it can be either a web app or a cli based app.


Web app debugging
First, we have to create a Server configuration:

File -> Settings -> Php -> Servers

Server configuration

Add a new server with its ip address (or hostname) and set the desired port. Check "Use path mappings" and map the vagrant's paths to the local ones.

The next step is creating a Run/Debug configuration:

Run -> Edit Configurations

Run/Debug configuration

Add a "PHP Web Application" config. Give it a name and choose the previously configured server from the select box.

To run our app in debug mode just go to:

Run -> Debug

and the web app will appear on a new tab in debug mode! If you want to restart the debug session again (after the actual one is disconnected) just refresh the page in the browser.

Cli app debugging:
At the start we should able to reach the host machine from our Vagrant box. So, how can we find out the host's ip?
"The IP address of the host is always the same IP address but with the final octet as a 1."
Okay, e.g.: if the vbox's ip is 192.168.33.10 we can ping 192.168.33.1 as our host machine from our guest.

We need the Server configurations as well (the same as the Web app debugging).

On the server side (in Vagrant) we've to create some environment variables:

export PHP_IDE_CONFIG="serverName=phpsaltbox"

export XDEBUG_CONFIG="remote_host=192.168.33.1 idekey=phpsaltbox"

serverName is the name what we typed in the Server configurations.
idekey comes from the xdebug config xdebug.idekey (it can be anything).

To run our cli app in debug mode we'll use the "Start Listen PHP Debug Connections" function in PhpStorm.

"Start Listen PHP Debug Connections" function


As the final step, just run your cli app in Vagrant and you'll see the debug window in PhpStorm in a couple of seconds!


References:

Monday, May 12, 2014

Symfony2 - DataFixtures

Fixtures are used to load a controlled set of data into a database. This data can be used for testing or could be the initial data required for the application to run smoothly (from symfony.com)
So, the DataFixture Bundle is a great way to help initialize your application, e.g. set up an admin user. You can use it all through the development phase continuously, it has an append option. Without the append argument your database will be erased before the fixtures get injected.

If you plan to use this bundle for testing, you can mix it up with the Faker library to create various test data.

When you work on a not so large project it's a good enough bundle to solve your problems. But if the project is a large one and you want to use a more sophisticated way to make fixtures you should use the Alice library! (it has a Bundle for Symfony2 -> AliceBundle)

Alice calls itself an Expressive fixtures generator. It has a lot of handy tools in its toolbox.

You can create fixtures in a config file! Let's see a Static one:
Nelmio\Entity\User:
    user0:
        username: bob
        fullname: Bob
        birthDate: 1980-10-10
        email: bob@example.org
        favoriteNumber: 42
    user1:
        username: alice
        fullname: Alice
        birthDate: 1978-07-12
        email: alice@example.org
        favoriteNumber: 27

Nelmio\Entity\Group:
    group1:
        name: Admins
Take a look at a Fixture Range config:
Nelmio\Entity\User:
    user{1..10}:
        username: bob
        fullname: Bob
        birthDate: 1980-10-10
        email: bob@example.org
        favoriteNumber: 42
The above fixture configuration ends up 10 users, from user1 to user10.

It integrates with the Faker library initially and has a several other helpful features.