PHP is a programming language for web development. PHP is released in 1995, when the Internet just starts spreading.

Now, PHP is widely used. For example, Facebook or WordPress is written in PHP. As it is widely used for web development, there are many opening job positions for PHP.

But, to develop PHP application in practice, you need to install and set up PHP or databases. These installations and setting up can be frustrating. Just following the installation instruction does not work or cause errors because of OS, versions, other software dependencies, etc.

Also, if you publish the service, feedback from your friends or others motivates you. However, this requires "deployment" of the service.
The "deployment" also frustrates us...

Just sign up with email and click a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

Click "new server" to open a dialog to set up the server.

Here, you can choose "PHP", "phpMyAdmin", and "MySQL", and click "New Server" button.

Just in 3 seconds, you'll get a browser-based development environment for PHP and MySQL.

You'll see editor or browser windows in the page, but we can close those for now.

Getting started with PHP

Now, let's run and show some PHP code.

On the left-side of PaizaCloud, you can see a file management view.
There is a file "public_html/index.php", so double-click to open it.

The file contains default code. Remove and replace with the following text.

public_html/index.php:

<h1>Hello</h1>

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

Then, open the file in the browser on PaizaCloud.

On the file management view, right-click the "public_html/index.php" file to show the context menu. Choose "Run in Browser". (Or, click the browser icon on the left side to open browser view, and type "http://localhost/~ubuntu/" in the URL bar on the browser.)

You see the text large "Hello". The text is just handled as HTML file.

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

On PHP, we embed the PHP code in the HTML file. To embed the PHP code, write the PHP code between "＜?php" and "?＞".
Here, we use "echo" command to output a string. The string is concatenated using "'Hello ' . 'PHP'", as "." operator concatenates the strings.

So, reload the browser view to update the web page.
(Or, if you close the browser view, on the file management view, right-click the "public_html/index.php" file to show the context menu, and choose "Run in the Browser". Or, click the browser icon on the left side to open browser view, and type "http://localhost/~ubuntu/" in the URL bar on the browser.)

Now, you see a text "Hello PHP", on the browser view. The PHP code was successfully run.
As this, the output of the PHP code can be seen as HTML.

Note that we can also write the PHP code on using "＜?=" syntax so that we can output the PHP output with more simple code.

<h1>Hello</h1><?=
'Hello ' + 'PHP';
?>

Let's try to calculate and output by changing the code, like "1+2", "3*3", "2**10"(10th power of 2).

Create database

You'll already have a MySQL server running because you checked it on the server setting. But if not, you can always manually start like:

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

Let's see the code.

On "$pdo = new PDO()", create a PDO object to use database. On the parameter, set MySQL server name("localhost"), database name("mydb"), username("root") and password("").

"isset($_POST['submit'])" test whether the code is run when the "Add" button is clicked, as the "Add" button form have a submit form with name "submit". Set the name of the todo to "$name" by fetching a value of the submitted text input form with name "name" as "$_POST['name'];".

On the "if" clause, create and run the SQL to insert the data into the database. To do that, we use prepare(), bindValud(), and execute() function of the PDO object.
"prepare()" is to set the SQL to manipulate the database, here we use "INSERT INTO todos" syntax to insert the row to the database. "bindValue()" is to replace the placeholder(":NAME") on the SQL with the value.
By not directly writing SQL with value, we can safely escape the value on the SQL statement. Then, "execute()" to run the SQL command.

"if(isset($_POST['delete']))" is the clause for deleting the todo item. As the "Delete" button have a hidden input field with the name "delete", the condition is true when the todo item needs to be deleted.
Retrieve the id of the todo as "$_POST['id'];", and run SQL statement "DELETE FROM todos" to delete the todo item with the id.

On the ”＜head＞" tag, load stylesheets for a simple CSS framework "milligram" using "＜link＞" tag.

On the "＜body＞", create an input form to add the item. Create a text input field with the name "name", and a submit form with the name "submit".

Show the todo list using "＜table＞" tag. "table" and "table-striped" class is a milligram class name to beautify the table.

Retrieve the table using PHP code inside "＜?php" and "?＞". "prepare("SELECT * FROM todos")" is a SQL to retrieve the todo list.

On "foreach($sth as $row)", scan all the row on the todos table by setting each row to "$row" variable.
On each table row, output todo item by using "＜?=" tag and "$row['name']" todo item value.
As the value may contain HTML tags, we need to escape the value using htmlspecialchars() to avoid security issues.

Then, on each table row, add a form with "delete" button, and hidden input field with value "$row['id']" to distinguish each item.

Don't forget to add "＜？php } ？>" to close the "foreach".

Run the application

Now, we wrote all the code. Let's see.

Reload the browser view to update the web page.
(Or, if you close the browser view, on the file management view, right-click the "public_html/index.php" file to show the context menu, and choose "Run in the Browser". Or, click the browser icon on the left side to open browser view, and type "http://localhost/~ubuntu/" in the URL bar on the browser.)

We see the "Todo List" page with the empty task.

Let's add or delete the tasks.

It works! We successfully created the Task List application with PHP and MySQL!

Note that on PaizaCloud free plan, the server will be suspended. To run the bot continuously, please upgrade to the BASIC plan.

Summary

With PaizaCloud Cloud IDE, we created a PHP application with MySQL database just in your browser, without installing or setting up any development environments.
Now, let's create your own Ruby on Rails application!

With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser.

Development Environment

We'll build the game using Node.js(Server Side JavaScript), Three.js(for WebGL), and Socket.IO(for networking).

While it is getting easier to build, to develop applications in practice, you need to install and setup Node.js and related commands or packages. These installations and setting up can be frustrating. Just following the installation instruction does not work or cause errors because of OS, versions, other software dependencies, etc.

Also, if you publish the service, feedback from your friends or others motivate you. But, this requires "deployment" of the service.
The "deployment" also frustrates us...

Just sign up with email and click a link in the confirmation email. You can also sign up with GitHub or Google.

Create new server

Let's create a new server for the development workspace.

Click "new server" to open a dialog to set up the server.
Just click "New Server" button in the dialog without any settings.

Just in 3 seconds, you'll get a browser-based online development environment for Node.js development.

Create a project

So, let's create the online multiplayer battle game using Node.js.

At first, to create the Node.js application, we use "npm init" command.

On PaizaCloud, you can use a Terminal application in the browser to run the command.

Click "Terminal" button at the left side of the PaizaCloud page.

The Terminal launched.
Type the command "npm init", and type enter key. You get the prompt "package name:", so type your application name like "game-app" or "music-app".

$ npm init
...
package name: (ubuntu) myapp
...

On the file management view at the left-side of the page, we see the file "package.json" created. The "package.json" is the file to manage Node.js packages used on the application.

To create the web application with Node.js, we'll need Express as a web application framework. So, let's install the Express package.
To install Node.js package, we can use the command "npm install [PACKAGE NAME] --save".

$ npm install express --save

The directory "node_modules" is created. The directory contains the packages used by the application.

Now, let's create the Node.js program. At first, we'll create a simple program just showing a text "Hello Node.js!".

On PaizaCloud, you can create and edit the file in the browser.
To create the program file, on the PaizaCloud, click "New File" button on the left-side of the page, or right-click file management view to open the context menu and choose "New File".

As a dialog box to put filename is shown, type a filename "server.rb" and click "Create" button.

After editing the code click "Save" button or type "Command-S" or "Ctrl-S" to save the file.

Let's see the code.

On the first and second line, it loads "express" library.

On line 4, "app.get('/'..." specify the action for the top page(URL path "/") as a function. It send a message 'Hello Node.js!' using "res.send()" function.

On line 8, "app.listen(3000,...)" run the Node.js server on port 3000.

Start Node.js

Now, you can run the application. Let's start the application.

On PaizaCloud, click "Terminal" icon to start Terminal and type "node server.js" to start the server!

$ node server.js

You'll get a new button with text "3000" on the left side of the page.

The server runs on port 3000.
PaizaCloud Cloud IDE detects the port number(3000), and automatically adds the button to open a browser for the port.

Click the button, and you'll get Browser application(a Browser application in the PaizaCloud).
Now, you'll see a web page with the message "Hello Node.js!", that is your application!

While you can run the Node.js server with "node server.js" command, it needs to restart when we change any code. So, from now, we use "nodemon" command that automatically restarts server when the program is changed.

Next, create a Player class to manage players. The Player class have instance variables "id" to identify the player, "with" and "height" for the size of the player, "x" and "y" for the position of the player, "angle" for the direction of the player, "movement" to store the player's current movement(which have forward, back, left or right boolean properties).

On the constructor, set "id" to random value, set size("width" and "height") to 80, set the player's position("x", "y") to the random value, and set "angle" to 0(right).

move() function moves the player's position with "distance" argument. We can get x-axis distance using Math.cos(), and y-axis distance using Math.sin(), and add those values to the current position.

The Node.js server and browser(client) communicate using Socket.IO.
io.on('connection',...) set the callback function when the connection is established. So, let's write codes for networking here.

socket.on('game-start',...) handle the message for starting game. Here, it creates a "Player" object and add it to the "players" variable.

socket.on('movement',...) handle the message for the player's movement. It just set the value received to the player's "movement" variable.

On socket.on('disconnect',...), callback function is called then the connection is closed(Ex: The browser is closed, the page is reloaded or changed.) Here, it removes the player from "players" variable.

Simple game(HTML)

Then, edit an HTML page for the top page "static/index.html".

On PaizaCloud file management view, right-click home directory("/home/ubuntu") to open the context menu, choose "New Directory" to create a directory named "static".
Right-click the "static" directory and choose "New File" menu to create a file "index.html".

The canvas element is for the game screen. As the canvas can show 2D figures, we use it for drawing players. The width and height for canvas size are 1000, and the size on the page is 100%(all of the page).

<imgid="player-image"src="/static/player.gif"style="display: none;">

Set the image for the player we'll upload later on. As the image is only for drawing canvas, we set the style to "display: no" so that we don't show the image here.

<scriptsrc="/static/game.js"></script>

At last, load a JavaScript program "static/game.js" we'll create.
Add the line at the end of BODY element so that the script runs after all the HTML file is loaded.

Simple game(Player image)

Prepare a player image file("player.gif").
Here, we use a paiza logo image below.

On PaizaCloud, we can upload files using Drag and Drop.

Save the "player.gif" file on the desktop, and Drag and Drop to "static" directory on the file management view of PaizaCloud to upload.

To move the player using a keyboard, handle 'keydown' and 'keyup' events.
The key name pressed is "event.key". Convert the key name to movement properties("forward", "back", "left", "right") using "KeyToCommand" hash.

movement[command] store the key state. It is true when the key is on, and false when the key is off. Send the movement object to the server using "socket.emit()".

On state.on('state',...), the specified callback function is called when the 'state' message(the player's state) is received. So, draw the player based on the state.

Clear the canvas with "clearRect()", and draw border rectangle of the game screen using "context.rect()". The functions like rect() to draw path requires "context.beginPath()" before the function, and "context.stroke()" after the function.

For each player, draw the image using "drawImage()", and write text 'Player' using "fillText()".

Run Simple game

Let's run the program.

To make sure, type Ctrl-C to exit current server.

Type "nodemon server.js" to start the server!

$ nodemon server.js

You'll get a new button with text "3000" on the left side of the page.
Click the button, and you'll get Browser application(a Browser application in the PaizaCloud).

Now, you'll see the players! Let's move the player with arrow keys.

You can run multiple browsers to run multiple players!

If it does not run, right-click the browser and choose "inspect" menu to see the error message. Confirm that the "static/player.gif" file exists on the server.

2D game(server)

While the "Simple game" is a kind of online multiplayer game, there are only players who can only move. Next, let's make the players shoot bullets to fight each other. Also, let's add walls, and play cannot move over the player or boundary of the game board.

In the "Simple Game" have only one class "Player". "2D game" also have "Wall" class and "Bullet" class. As those "Player", "Wall", and "Bullet" class are objects existing on the game board. So, we create a GameObject class for common parts for those classes on the game board.

Also, for the test playing or for the case there is no other players on the game board, we create a bot player class "BotPlayer" inherited from the "Player" class.

"GameObject" class represents objects existing on the game board.
The constructor function generates "id" from a random value. "x", "y" represents the position, "width", "height" represents the size, and "angle" represents the direction of the object. Those variables can be passed as a argument of the constructor.

move() of GameObject moves the object for the "distance" parameter. Use Math.cos() to get the distance in the x-direction, and "Math.sin()" to get the distance in the y-direction. It also test that the position moving to is not out of the game board by testing that the "x" is between 0 and FIELD_WIDTH - this.width, and "y" is between 0 and FIELD_HEIGHT - this.height.
Also, it test that the object is not collided with walls using intersectWalls() we'll create later on.

The function returns true if moving succeeded, or move back to the original position(oldX, oldY) and return false if the object collides with walls or boundaries.

The intersects() of GameObject test if the object collides with the other objects. As GameObject represents the rectangular object, it tests whether there are any intersections of objects for x-direction, and y-direction.

The toJSON() function of the GameObject represents how to transform the object to JSON format for sending the object to the client. Here, we use "id", x", "y", "width", "height", and "angle" variables.

JSON.serialize() will use this "toJSON()" function to create the JSON string from the object.

Player class inherits GameObject class, and have "socketId" variable for communication socket, "nickname" variable for the nickname, "health" variable for the player's health point, "bullets" for the collection of the bullets the player shot, and the "point" variable for the points. It set the initial "health" to 10, and the maxHealth to the initial "health".

The player's position is set using random value. If the position is in the wall, other position is created.

The shoot() function of the Player class shoot bullets. Let's set the maximum number of concurrent bullets to three. If there are already three or more bullets exists, it does not shoot more bullets.

It creates the bullets objects with "new Bullets()". It set the position of the bullets to the center of the player. Also, call "player.move(this.width/2)" to move the bullet to around the edge of the player.
It keeps the bullets shot to the "bullets" variable.

damage(){this.health --;
if(this.health === 0){this.remove();
}}

The damage() of the Player class represents the action on the damage when the player was shot. It decreases the "health" by one, and remove the player if the health is zero.

The toJSON() of the Player represents the list of variables of the object used when the object information is sent to the browser(client).
Here, we use "health", "maxHealth", "socketId", "point", and "nickname" variables in addition to the variables set on the toJSON() of GameObject class.

As a bot player a kind of the player, BotPlayer class inherits Player class.
In the constructor function, it moves the bot player on every 1/30 seconds using a timer. When the move() fails, it changes the direction of the player randomly. It also shoots bullets randomly.

The remove() function is called when the bot was killed. It creates a new bot after 3 seconds.

For each player of the "players", move the player based on player's "movement" variable.

For each bullet of the "bullets", move the bullet. If the bullet reaches to the edge of the game board of the walls, the bullet is removed. If the bullet collides with any players, then remove the player's health using damage(), remove the bullet, and increase the player's point by one.

After the movings, send the positions and other statuses of the players, bullets, walls to the browser(client) as 'state' message.

When the client receives the 'state' message from the server, draw the objects.

For each player of the "players" variable sent, draw "nickname" and "health" using context.fillText() function. It also draw the player's image("playerImage") using context.drawImage(), with context.translate()/context.rotate() to rotate the player to the direction specified by "angle".

If the player's "socketId" and the socket's is the same, the player is the current player. So, add the text 'You' to the player image, and show the point of the player.

For each bullet of the "bullets" variable sent, draw a circle using "context.arc()".

For each wall of the "walls" variable sent, draw a rectangle of the wall size.

socket.on('dead', () => {
$("#start-screen").show();
});

When the 'dead' message representing the player's death, it shows the start screen.

2D game(client, mobile)

Now the game support keyboard input, but it cannot be played from smartphones(mobile devices). So, let's handle the touch events to make it possible to play the game on the smartphones. To make it simple, "tap" shoot a bullet, "tapping" moves the player, and sliding will change the direction of the player to left or right.

Add the code below to the browser(client) JavaScript code "static/game.js".

On the "touchstart" event handler, it sends the 'shoot' message to the server to shoot a bullet, and set "move.forward" to true to move forward. It stores the position of the touch starts to "touches" variable.

On the "touchmove" event handler that is called when the touch position is changed, it changes the player direction left or right when the position is changed over 30.

On the "touchend" event handler that is called when the touched finger is left from the screen, it removes the touch from "touches" variable. If all the touch event ends, the movement is cleared.

Run 2D game

Let's run the 2D game program.

To make sure, type Ctrl-C to exit current server.

Type "nodemon server.js" to start the server!

$ nodemon server.js

You'll get a new button with text "3000" on the left side of the page.
Click the button, and you'll get Browser application(a Browser application in the PaizaCloud).

Now, you'll see your player and bot player! You can move the player using arrow keys, and shoot bullets using space key. If your health reaches zero, the game is over.

As it is a multiplayer game, you can play with your friends. On the smartphone, you can play using finger touches.

3D game (HTML)

2D game is already enjoyable enough. But, the 3D game is more powerful, let's change the 2D game to the 3d game.
Here, we use Three.js library to do 3D rendering with WebGL.

Set the position using "position" property, and rotate by setting "rotation" property. Here, as we create a plane on X-Y plane (0,0)-(1000,1000), set the position representing the center of the object to (500,500). As the plane is vertical, rotate -PI/2 to make the plane horizontal.

Demo

Summary

With PaizaCloud Cloud IDE, we created a 3D online multiplayer game just in your browser, without installing or setting up any development environments. We run the server in PaizaCloud so that we can play the game with friends, or anyone in the world!
Now, let's create your own games!

With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser.

Now, there are 3 major web application frameworks: Ruby on Rails, Django, Laravel.

All of those are full-stack frameworks having all the major features to build web applications. But, each has their own feature, structure, philosophy, or programming language.

You may hear the name of those frameworks, but not so many developers actually have used all those frameworks.

Even if you are comfortable with your favorite framework, other frameworks will show you the web application development from different angles.

At the same time, you may not understand the features and feel the atmosphere just by browsing the list of features. So, I'll show the features and differences of those web application frameworks by actually creating ToDo list applications with Ruby on Rails, Django, and Laravel.

Here, we'll create the web application using cloud IDE PaizaCloud so that we don't need to install and set up the development environment for all the frameworks. So, let's build the application together!

Trend of Web application frameworks

At first, let's see the trends of Ruby on Rails, Django, and Laravel on Google trends and Stackoverflow Trends.

All of Ruby on Rails, Django, and Laravel have quite similar popularity, at now.

I can say that Ruby on Rails go over the fever, Django is stable, and Laravel is growing.

Comparison

Next, let's see the strength of each framework on the comparison sheet.

Ruby on Rails and Django was released on the similar date, but Laravel is newer.

Ruby on Rails and Laravel have many features like code generation, and allow you to build the applications by writing only a little codes. But, Django have less "magic" and ask you to write code explicitly so that you code can be more readable.

As it is a bit of cumbersome to set up development environments for Ruby on Rails, Django, and Laravel, we'll use PaizaCloud, a cloud-based web development environment. PaizaCloud is a browser-based web development environment supporting Ruby on Rails, Django, Laravel. So, you don't need to locally install and set up your development environment.

Ruby on Rails is an opinionated framework with philosophies: Don't Repeat Yourself(DRY), Convention over Configuration(CoC). Just by following the "rails", you can build the well-structured large scale web application naturally.

Ruby on Rails has many smart features for web developments. MVC, scaffolding, generator, migration, routing, model, controller, ORM(Active Record) changes the way to develop web applications. "Ruby" as an object-oriented scripting language and "Ruby on Rails" is the best partner for web developments that require speedy and flexible development.

The development of Ruby on Rails is quite active. Recent release added webpack for front-end development.

Let's see the file structure on the file manager view. The "app" directory have controller, model, view subdirectories.

Let's see the model file. There is almost no code on the file. Ruby on Rails have ActiveRecord that allows you to access database table as Ruby class, so you don't need to write code to access the database.

myapp/app/models/todo.rb:

classTodo < ApplicationRecordend

Let's see the controller. It has CRUD actions(creating, reading, updating and deleting). As the instance variable "@NAME" can be referred from view, you can set those variables to show in the browser.

Let's see the view file. It is an HTML file with ERB with "＜% %＞"、"＜%= %＞" blocks.
"＜% %＞" syntax allows you to run the ruby code inside, and "＜%= %＞" allows you to embed the result of the ruby code to show in the browser.

Django is the most popular web application framework in Python.
Python is getting more popular for AI and machine learning.

As Django does not magically generate so many codes like Ruby on Rails, you need to explicitly write more code by yourself. But, it means, you can write lean and readable code.

Django is a full-stack framework with many features for web development. You can also utilize a bunch of Python libraries including libraries for machine learning.

Django also has a feature for admin pages, so you can easily create admin pages for browsing or editing database tables.

Django development is active, and the latest Django2.0 was just released in December 2017.
In Python, it is often a controversial topic to choose whether Python2 or Python3. But, as Django2.0 only support Python3, you don't need to care about it and just use Python3 with Django2.0.

So, let's start building a web application in Django.

At first, click Terminal button on the left-side of PaizaCloud.

$ django-admin startproject mysite
$ python3 manage.py startapp todo

In Django, you can have multiple application in one project. Here, let's create a project "mysite", and an application "todo" inside the project.

PHP itself was created as an HTML template engine, and one of the oldest web development language. While you can easily start writing web applications, it is often difficult to create large web applications.

But, Laravel utilized modern features like object-oriented syntax, the package manager(composer), MVC, generator, model, migration, ORM(Eloquent), the template engine(Blade) or DI, and make it possible to build readable large-scale applications in PHP.

PHP is widely used on many web sites or tools like WordPress, Laravel have the advantage to use PHP based resource and knowledge.

Now, let's create a web application in Laravel.

Click Terminal icon on the left-side of PaizaCloud.

Create a project with name "myapp".

$ laravel new myapp
$ cd myapp
$ php artisan serve

Create a database "mydb".

$ mysql -u root
create database mydb;

Edit the database configuration file. Right-click on file manager to open context menu, choose "Show Hidden files" to show files begun with a dot('.').

myapp/.env:

DB_DATABASE=mydb
DB_USERNAME=root
# DB_PASSWORD=secret

Create model, controller, and migration file with one command.

$ php artisan make:model Task -m -c -r

In the migration file, add "$table->string('name');" to add "name" column to the database table.

Summary

We compared the big 3 web application frameworks: Ruby on Rails, Django, Laravel, by building the real application with database. All of those are full-stack frameworks with many features.

With PaizaCloud, We could build the real application without installing and setting up the development environment. I believe that the best way to know about the frameworks is to create applications by our hands. Let's try by yourself!

With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser.

With iPad, we can edit e-mail, browse the web, create documents or spreadsheets or presentation, browser photos or movies quite handy. With millions of applications on App Store, iPad can even be more useful than PC.

Isn't it more useful if we can develop web or other applications on iPad?

So, here comes PaizaCloud Cloud IDE.
PaizaCloud is a browser-based web development environment in the Cloud.
With PaizaCloud, we can develop web applications or other applications on iPad!

PaizaCloud supports iPad, and have browser-based editor, terminal, browser-in-browser, file manager for building applications.
PaizaCloud has development environments like Ruby on Rails, Django, Node.js, Laravel, PHP, Java(tomcat), MySQL, Jupyter Notebook... You don't need to struggle with annoying installing and setting up development environment.

As you can use the same environment from any devices, you can develop on PC today, and continue development on a cafe using iPad tomorrow.

In this article, we actually build a BBS application on iPad using PaizaCloud and Ruby on Rails. We can build the application just in 10 seconds just following the instruction.

The '[application name]' is the name of the application you are creating. You can choose whatever you want, like "music-app" or "game-app".
Here, I'll choose the application name "myapp", where I can manage the list of posts.

Also, let's add "--database=mysql" to use MySQL database.

So, lets type:

$ rails new myapp --database=mysql

In the file finder view at the left side of the page, you'll see the "myapp" directory. Tap the folder to open it to see inside the directory.

You'll see a bunch of files for the Ruby on Rails application.

You'll already have a MySQL server running because you checked it on the server setting. But if not, you can always manually start like:

Although we used PaizaCloud on floating window mode, you can switch to tab windows mode for full-screen editing by tapping window bar's maximize button, or by tapping blue button with PaizaCloud button to open a menu and choose "Tab Window Mode".

Summary

With PaizaCloud Cloud IDE, we created a Ruby on Rails application on iPad.
Now, let's create your own Ruby on Rails application!

With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser.

Although we can build web applications only by using Go's rich standard library, web application frameworks make it easier
to develop the full-fledged web applications.

There are many Go web application frameworks like Revel, Echo, Gin, Iris, Revel is one of the most popular full-stack web application framework.

Go framework Revel has features for web development like routing, MVC, generator. By building the application following Revel rules, you can naturally create readable and extensible Web Applications. You can also use OR mapper library like Gorm with the Revel.

But, to develop Revel application in practice, you need to install and setup Go, Revel, Gorm, or databases. These installation and setting up can be frustrating. Just following the installation instruction does not work or cause errors because of OS, versions, other software dependencies, etc.

Also, if you publish the service, feedback from your friends or others will motivate you. But, this requires "deployment" of the service.
The "deployment" also frustrates us...

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

Let's see the code.

On "InitDB()" function, it reads the DB settings from "db.info" line of the configuration file, and open the database using Gorm library. Then, "db.AutoMigrate()" creates a table from Post model we'll create later. It assigns the database handle to "DB" variable so that other files can access the database as "controllers.DB".

There are two lines to add. The first change is to add "myapp/app/controllers" to "imports", and the second change is to add "revel.OnAppStart(controllers.InitDB)" at the end of init() function to call "InitDB()" on "germ.go" we just created.

Create table, model, etc.

Next, let's create a database table.

With Gorm library, we can manipulate the database using model information written in Go struct.

Right-click the "go/src/myapp/app" directory to open the context menu, and choose "New directory" menu, and create "models" directory.
Right-click the "go/src/myapp/app/models" directory to open the context menu, and choose "New File" menu, and create "post.go" file.
Then, edit the created "app/models/post.go" file like below.

Add "myapp/app/models" to "import" so that we can access the Post model.
Create Post controller at "type Post struct".

"func (c Post) Index() revel.Result" is a Index() method of the Post controller to return the Todo list.
"posts := []models.Post{}" create "posts", an array of Post model.
'DB.Order("id desc").Find(&posts)' retrieve all the "posts" table records, and store them to the "posts" array.
Then, if there is no error, call Render() method to create the HTML file. The HTML file is created from the HTML template we will create later on. By setting "posts" to Render() argument, the template file can refer the "posts" table.

"func (c Post) Create() revel.Result" is Create() method of the Post controller to create a Todo.
"models.Post{...}" creates a model, retrieve the "body" parameter of the submitted form using "c.Params.Form.Get()", and set it to "Body" field of the model.
"DB.Create(&post)" create a database record from the model. Then, redirect to the Todo list page using 'c.Redirect("/posts")'.

"func (c Post) Delete() revel.Result" is a Delete() method of the Post controller to delete a todo.
'c.Params.Route.Get("id")' get the ":id" part of the URL: "/posts/:id/delete".
"DB.Delete(&posts, id)" deletes an record of the "id".
Then, 'c.Redirect("/posts")' redirects to the Todo list page.

"func (c Post) RedirectToPosts() revel.Result" is to redirect from the top page to Todo list page.

Create HTML template

Next, let's create HTML a template.
An HTML template is an HTML file with embedded code.

Create an HTML template file to list, add, and delete Todo as "app/views/Post/index.html".

Let's see the template file.
On the HTML template, a part between "{{" and "}}" is to describe actions which creates HTML.

'{{set . "title" "Todo list"}}' sets "title" variable as "Todo list".

'{{template "header.html" .}}' creates HTML file from a template file "header.html".
By calling other HTML templates like this, we can share common parts for multiple template files as the one template file.
Here, "header.html" have common HTML header part.

'＜form action="/posts" method="post"＞' is to create a Todo form.

'＜input type="text" name="body" class="col-xs-8"＞' shows a text input form to input a Todo.
Set form name to "body" so that "body" parameter of the submitted request has the inputted Todo.

The part between '{{ range .posts }}' and '{{ end }}' is read through posts array, and create HTML from HTML template inside repeatedly for each post.

'{{ .Body }}' shows the "Body" field of each post. '{{.ID}}' shows the Id field of each post.

Run the application

It works! We successfully created the Task List application with Go/Revel!

Note that on PaizaCloud free plan, the server will be suspended. To run the bot continuously, please upgrade to the BASIC plan.

Summary

With PaizaCloud Cloud IDE, we created a Go/Revel application just in your browser, without installing or setting up any development environments. We can even publish the application just on the PaizaCloud.
Now, let's create your own Go/Revel application!

With「PaizaCloud Cloud IDE」, you can flexibly and easily develop your web application or server application, and publish it, just in your browser.

Python is one of the most popular programing languages. With libraries for machine learning, Python is getting more popular.

Python is a script language. As the Python code can run from one line, it is quite suitable for learning programming. Actually, there is a data that Python is the most popular language to teach in the US universities.

To develop web application with Python, there are several web application frameworks like Django, Pyramid, Flask, Bottle, etc. But among that, Django is obviously the most famous web application framework in Python.

Django is a full stack web application framework with MVC, ORM, generator, etc. By following Django way, you can easily build a well-structured web application.

The latest Django2.0 was just released on Dec 2017. It used to be bothering to think which of Python2 or Python3 to use. But, now, as Django2.0 only support Python3.0, there is nothing to worry about Python version. Now is the good time to start Django!

But, to develop Django application in practice, you need to install and setup Python, Django, or databases. These installation and setting up can be frustrating. Just following the installation instruction does not work or cause errors because of OS, versions, other software dependencies, etc.

Also, if you publish the service, feedbacks from your friends or others will motivate you. But, this requires "deployment" of the service.
The "deployment" also frustrates us...

Here, I'll choose the project name "myapp", where I can manage the Todo List.

So, lets type:

$ django-admin startproject mysite

In the file manager view at the left side of the page, you'll see the "mysite" directory. Click the folder to open it to see inside the directory.

You'll see a bunch of files for the Django application.

Editing file

To run Django on PaizaCloud, you need to edit a file "setting.py".
On file manager view, double-click the file "mysite/mysite/settings.py" for editing.

Edit the line "ALLOWED_HOST = []" as following.(By this setting, you can connect the application with host name other than "localhost". Even if you change the line, for the server listening on "127.0.0.1", other than the owner user of the server cannot connect to the server.)

ALLOWED_HOSTS = ['*']

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

After the editing, click "Save" button or type "Command-S", or "Ctrl-S" to save the file.

On Django, the action to show the page is created as a view function. The view function returns the contents of the page. To show the simple text, we can use "HttpResponse()" function to specify the message to show.

Then, we create a file "urls.py" to set the relations(routings) between URL and view function.
The URL routing file for the ToDo application is "mysite/todo/urls.py".

Let's see the code.
On "urlpatterns" list, we call path() function to set URL, view function, and the name of the routing.
Here, we set ''(empty string) to URL, "index" function to the view function, and the name to the "index".

Next, to use the application on the project, set the URL routing for the project.
URL routing file for the project is "mysite/urls.py", so let's edit the file.

Let's see the code.
On the first item of the "urlpatterns" list, we set the routing for the path '/todo' to "include('todo.urls')" so that the routing settings under '/todo' path can be specified on the file "mysite/todo/urls.py".

On the third item, we set to redirect the top page('/') to "/todo". We use "RedirectView.as_view()" function to set the redirection. We are importing the RedirectView on the third line.

Then, to use the application on the project, edit the settings file("mysite/mysite/settings.py") to add "todo.apps.TodoConfig" to the INSTALLED_APPS list.

Let's see the code.
"app_name" need to set to the ToDo application name('todo').

On "urlpatterns" list, we set the routings.
On the first item, we set the path '/todo' to call "index" function of "mysite/views.py".
On the second item, we set the path '/todo/create' to call "create" function of "mysite/views.py".
On the third item, we set the path '/todo/<int:id>' to call "delete" function of "mysite/views.py".
By writing the part of the path like "<int:id>'", we can retrieve the part from the program.
For example, for the path "/todo/1", we can get the "1" as variable "id".

View settings

Let's write the view code called from the routing.
Write functions for listing, adding, and deleting the item as index(), store() and destroy().

Let's see the code.
On line 4 and 5, we import the model and form class from "models.py", "forms.py".

On the index() function, we call the Post.objects.all() function to retrieve all the ToDo items from the database. The retrieved data is set to the dictionary "context" with the key "posts" so that HTML templates can access the ToDo list as "posts" variable. On the "form" key, we set the empty PostForm object as a value for the submitting form.

On the create() function, we create a PostForm object from the parameter submitted, and call form.save() to save the data to the database. Then, we redirect the request to '/todo' for listing ToDos.
We use HttpResponseRedirect() for the redirection. We use reverse() function to convert from the routing name to the URL.

On the delete() function, we call get_object_or_404() function to retrieve the object for the ToDo ID(id). We use post.delete() to delete the object, and redirect to '/todo' like create() method.

Creating HTML template

Then, let's create HTML templates. On HTML templates, we embed the code on the HTML file.

The HTML file can be written in one file. But, as it is more easy to have a common layout file for multiple template files, we create the layout file.

We create the layout file as "mysite/todo/templates/todo/base.html".

On file management view, right-click the directory "mysite/todo", and choose "New Directory" menu, and create the directory with the name "templates".

Next, right-click the directory "mysite/todo/templates" and choose "New Directory", and create the directory with name "todo".

Then, right-click the "mysite/todo/templates/todo" directory and choose "New file" menu, and create the file with name "base.html".

The line "{% extends 'todo/base.html' %}" specify to use the layout file('todo/base.html').

The contents between "{% block content %}" and "{% endblock content %}" is for the page contents.
The contents replace the "{% block content %}{% endblock %}" part of the layout file("todo/base.html").

The first form is for adding to ToDo. On Django, the form need to have like "{% csrf_token %}" to protect from CSRF attack.

The "input" tag can be generated by writing the field of PostForm object like "{{ form.body }} ".
The like will generate the input form like '<input type="text" name="body" id="id_body" maxlength="200">'.

The form is set to submit to "POST /todo".

On the ToDo listing, we can use "posts" list to access the ToDo items. By writing "{% for post in posts %} ... {% endfor %}", we can set each ToDo item to "post" variable.

"{{ post.body }}" is the Django HTML template format to show the contents of "{{}}". Here, we are accessing "body" property of the "post" object to show the "body" column on the database.

On the "Delete" button, we call "POST /todo/{id}/delete" to delete the specified task.

Laravel has features for web development like routing, MVC, ORM, generator. By building the application following Laravel rules, you can naturally create readable and extensible Web Applications.

But, to develop Laravel application in practice, you need to install and setup PHP, Laravel, or databases. These installation and setting up can be a frustrating. Just following the installation instruction does not work or cause errors because of OS, versions, other software dependencies, etc.

Also, if you publish the service, feedbacks from your friends or others will motivate you. But, this requires "deployment" of the service.
The "deployment" also frustrates us...

Next, create a database for the application. Here, we create a database "mydb" using "mysql" command.
Type the command below to create the "mydb" database.

$ mysql -u root
create database mydb;

You created the database.

Then, set the application to use the database.
Database configuration file is ".env" under the project directory.
Files begin with a dot('.') is hidden files that are not visible in the file manager view by default.
To make it visible, right click on file manager view and choose "Show Hidden files..." menu.

Then, open the ".env" file and edit 3 lines for "DB_DATABASE"、"DB_USERNAME"、"DB_PASSWORD" settings.
As there is no password for the MySQL, comment out for "DB_PASSWORD" setting.

myapp/.env:

DB_DATABASE=mydb
DB_USERNAME=root
# DB_PASSWORD=secret

Create table, model, etc.

Now, let's make application to use the database.

On Laravel, we can create a database table, a model class, and a controller class with "php artisan make:model" command.

Run the command below. The "-m" option is for creating a migration file, the "-c" option is for creating a controller file, and the "-r" option is for creating controller methods related to resource handling.

$ php artisan make:model Task -m -c -r

The command creates following files.

Filename

Role

database/migrations/2018_xx_xx_xxxxxxxx_create_tasks_table

Migration file

app/Task.php

Model

app/Http/Controllers/TaskController.php

Controller

The migration file has settings to create a table. Now, let's add a column "name" for the task name.
Add "$table->string('name')" to Schema::create() calling like below.

Let's see the code. Rout::get is for GET method. The second argument is for setting action using the callback function, or the controller class and action name. For about 'GET /' request, redirect to '/tasks' using the redirect() function.
For about 'GET /tasks' request, set the action to call TaskController's index() method.
For about 'POST /tasks' request, set the action to call TaskController's store() method.
And for about 'DELETE /tasks/{id}' request, set the action to call TaskController's destroy() method.
By writing like "{id}", we can get the part from the PHP code. For example, for about "/task/1" request, we get "1" as $id .

And, as PaizaCloud uses HTTPS protocol to access the server, add "\URL::forceScheme('https')". Without this setting, redirect() does not work.

To make sure, let's set to use HTTPS in the application settings. As we can set application wide settings on "AppServiceProvider.php"'s boot() method, add "\URL::forceScheme('https')" to the file like below.

"use App\Task" is written to use Task class. Without the "use", we need to write "Task" as "\App\Task".

On index() method for listing tasks, use Task model's Task::all() method to retrieve all the tasks from the database table.
Call view() function to render the page. The first argument is setting view file, and the second argument is to set variable names referred on the view file. We set the retrieved tasks to the value of 'tasks' key on the associated array so that the view file can refer tasks as $tasks variable.

On store() method for adding a task, create a Task object and set the submitted name parameter to name property of the Task object, and call $task->save() to save the task to the database. Then, redirect to '/tasks' to show the Task listing page.

On destroy() method for deleting a task, call Task model's Task::find() method to retrieve a task for the task id($id). Call $task->delete() to delete the task, and redirect to '/tasks' to show the Task listing page.

Create view(HTML)

The view can be just one file. But, as we can have a shared layout for multiple view files, let's create the layout file for now.

Now, we create the layout file with the filename "resources/views/layout.blade.php".
To create the file, right-click on the "resources/views" folder and choose "New file" menu, then set filename to "layout.blade.php".

On the file, we use simple CSS framework "Milligram". Milligram makes HTML files beautiful without writing additional class names.
On "body" tag, there is a line "@yield('content')", here is the place to replace with the page content.

Then, create a file for listing tasks, creating or deleting a task with the filename "resources/views/tasks.blade.php".

Let's see the file. The line "@content('layout')" is to specify to use the layout file('layout.blade.php').
The area between "@section('content')" and "@endsection" is for the content of the page. The layout file's "@yield('content')" part will be replaced with this content.

The first form is to create a task. On Laravel, we need to add "{{ csrf_field() }}" for CSRF prevention.

On the "input" tag, we set the name to "name" for the task name. The form is set to submit to "POST /tasks".

On the task list, we can refer the task list object as $tasks array. "@foreach ($tasks as $task)" is Blade syntax. It can be written in PHP as "<?php foreach($task as $task){ %>" where we can get each task as $task variable from $tasks array.

The "{{ $task->name }}" is also Blade syntax. "{{...}}" is to show the value inside braces. It can be written in PHP as "<?= $task->name ?>".
Here, we refer name property of the $task object to access the "name" column of the "tasks" table on the database.

On "Delete Task" button, set the form to call "DELETE /tasks/{id}" to delete the task. As HTML cannot handle the DELETE method directly, we use "method_field('DELETE')" to emulate the DELETE method.

Model file

Let's see the model file. The model class is empty like below.

Actually, we don't need to set anything. Laravel provides ORM called Eloquent, where table column can be referred as model's property automatically. Isn't it cool?