Introduction to Ruby on Rails

Introduction to Ruby on Rails

Have you been wondering how to build a web application? Perhaps you have started to learn programming languages but realizing that you had so much to climb the mountain and end up giving up. Or maybe you have been developing websites but it has been hard for you to maintain, keep track or upgrade your web application. In this article, we will learn about ruby on rails and the reasons behind using it as your backend development framework. I will also show you how to setup Ruby on Rails development environment and create a simple todo list application in few minutes with Ruby on Rails.

Getting to know Ruby on Rails

So let us address Ruby for a while before we go deep into this topic. Ruby is a programming language that was developed by Yukihiro Matsumoto from Japan in 1995. The idea of Ruby programming language is to put human need above computer needs, that is why Ruby is an object-oriented yet easy-to-use scripting language.

Okay, now we have a bit of history about Ruby programming language so let us talk ruby gems. Wait don’t get confessed yet, I am not talking about “a pink to blood-red colored gemstone”. What I talking about it is “a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries, a tool designed to easily manage the installation of gems, and a server for distributing them”  that is conveniently named RubyGems.

Alright, let’s take a breather…

Since we know that Ruby is a “human-friendly” programming language creating RubyGems was essential to making the language more powerful for a longer time.

Okay, know most probably you are wondering so what is it about Rails then? 

In simple words, Rails is one of RubyGems. Rails is just a package that enables Ruby to run a webserver. So what is so special about it you might ask.

Rails

To begin with, Rails gem is not “only a package” but it is an entire framework for web development. Rails framework is built with the developers are in mind to keep the process of development as easy as it should be. It also has an easy learning curve compared to other frameworks. 

Oh boy, we are going into a bit of detail here but don’t worry it will all make sense eventually. 

Let start with, “Rails is a model-view-controller (MVC)” framework. 

Wait hold your horses… “MVC” what is this a channel name, something like MTV? 

Well, that would be awesome, but I am sorry; it is not a channel name. 

“MVC is an architectural pattern that separates an application into three main logical components. Each of these components are built to handle specific development aspects for an application” -wiki 

Sound complicated? Not really. Here how Rails MVC works: 

  • Model: is Responsible for storing and retrieving data
  • View: is Responsible for the rendering of the model (User interface)
  • Controller: is Responsible for responding to user input and instructing the model to respond to the user input 

A simple animated illustration is shown on how Rails MVC work is shown below:

Ruby on Rails Model-View-Controller (MVC)

Reasons why

Why Rails? Well, I will give you the reasons and you can be the judge of “why not rails?”

1. The process of development is much faster 

Due to the object-oriented nature of Ruby and the enormous collection of open source code available within the Rails community, Rails development process is much faster compare to other programming languages.

2. Developers find it easy to move between different Rails projects

As developers working in many projects, keeping track of what different project code doing could be hard. But not in rails because of each project your create uses the same structure and coding practices.

3. Rails is good for rapid application development (RAD)

Because it is easy to accommodate changes, Rails is a great framework for rapid application development; were RAD is a methodology that prioritizes fast prototype releases and repetitions.

4. Ruby code is “humanize code” and mostly self-documenting

Because Rails is build using Ruby, it takes advantage of ruby’s readability. which makes rails easy to pick up by other developers with code that has less documentation.

5. Develops a strong focus on testing

Rails have a strong testing framework that can test your application before deployment and helps developers find bugs or security threads.

6. Open source code

There are no licensing costs associated. Since Rails libraries are mostly open-source it is free to use for commercial uses, unlike other frameworks that have paid licensing.

Common concerns about ruby on rails

1. Hosts support for Rails

The support of hosting companies for Ruby on rails is not common. Comparing to PHP, javascript, Java, and C to Ruby, Ruby is a slow programming language. But it should not be a deal-breaker. With hosting providers like Heroku and EngineYard, you can deploy your application for the world to see in minutes.

2. Performance and Scalability

Rails applications are not as fast as Java or C, which is true. it does not stop big companies to rely on Rails as their primary framework. Big companies such as Airbnb, Twitch, Kickstarter and many more. The majority of applications developed by Rails are fast enough. Although Ruby on Rails is not the fastest programming language.


Ruby on Rails Development Environment setup

Setup on Mac/Linux machines

Installing homebrew (MAC/Linux)

Start by installing homebrew in your mac machine. To do so you have to run the following command in your terminal:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Installing Ruby (MAC/Linux)

Now that we have Homebrew installed, we can use it to install Ruby.

We’re going to use rbenv to install and manage our Ruby versions.

To do this, run the following commands in your Terminal:

brew install rbenv ruby-build

# Add rbenv to bash so that it loads every time you open a terminal
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.zshrc
source ~/.zshrc

# Install Ruby
rbenv install 2.7.0
rbenv global 2.7.0
ruby -v

Installing Rails (MAC/Linux)

Installing Rails is as simple as running the following command in your terminal:

gem install rails -v 6.0.2.1

Rails is now installed, but in order for us to use the rails executable, we need to tell rbenv to see it:

rbenv rehash

And now we can verify Rails is installed:

rails -v
# Rails 6.0.2.1

Setting Up A Database for macOS Searia

Rails ships with sqlite3 as the default database. Chances are you won’t want to use it because it’s stored as a simple file on disk. You’ll probably want something more robust like MySQL or PostgreSQL; but for our purposes, we will only need a simple setup to get started.

Because we can’t use the built-in sqlite3 version with macOS Sierra without running into some troubles, we’re going to install from homebrew.

brew install sqlite3

Setup on Windows machines

Installing Ruby (Windows)

To install Ruby for windows, you can go download the ruby installer and install it like any other application

Once you installed ruby go ahead and open the command prompt. to confirm ruby successfully installation you can type the following command

ruby -v 

Installing Rails (Window)

After installing ruby you can open the command prompt and type the following to install Rails

gem install rails

once you installed Rails, you can verify by typing the following:

rails -v 

and that should be it for windows users, lucky you windows user!

Creating your first Rails Application

Generate Rails Application Files

After installing Ruby on Rails we can start with creating a simple application to see how fast and easy it is to make solid applications using Rails. open your terminal/command line then navigate to where you want to create your project using cd command for example cd Desktop/

to create a new rails project you can type the following command:

rails new <name_of_your_project>

For our example, we are going to make a simple todo list application so if you want to follow along with type the following code instead:

rails new todolistapp

Creating a Database for Your Rails Appliaction

Then press enter and wait for the magic to happen. once rails finish generating your todo application you have to navigate to the newly created project folder:

cd todolistapp

then run the following code to create the database for your application

rake db:create

Starting Rails Server

once created the database try to run the rails server by typing

rails s

or

rails server

After run the rails server you can open a new browser window and load http://localhost:3000/ to view your newly created rails application.

Using rails scaffold to create a simple todo list application

Okay, you have come through so far. now we have a todo list app created and our server is loading the rails default page.

will now let us make it our own and change it to our needs.

let us list down the “todo list” for our todo list app: (sound funny when you put it this way) anyhow here:

  • database table for the todo list app.
  • model to update the database.
  • views to display the model data.
  • a controller that takes the user input and sends back view.

doesn’t that sound a lot todo? Well, it is a lot to do for creating a simple app like this! But not with Rails.

you can use two commands to do all of this for you.

Generate Scaffold

if you were following along and you still have the rails server open, you can press control-c into the terminal/command line to exit from the rails server first.

In the terminal, you can use this first command to create a scaffold:

rails g scaffold List title:string done:boolean

or

rails generate scaffold List title:string done:boolean

Database Migration

Then run the following code to create the database table for the list

rake db:migrate

and yes that is it you have created your first todo list application using rails.

Start Rails Server

run the server again using :

rails s

then go to http://localhost:3000/lists and test it yourself.

Changing the default route

now when you go to http://localhost:3000/ you still have the default rails page to get rid of it you should define a route to your application.

to do so you can open your project using Atom text editor if you have it installed by typing the following in your terminal

atom .

or just open the project folder with any text editor you currently have.

then navigate to config > routes as shown in the screenshot below:

once you open the file you can add the following :

root "lists#index"

your routes file code should look something list this:

Rails.application.routes.draw do
  resources :lists
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root "lists#index"
end

Adding bootstrap styling to your rails application

If you are following along, you have created an ugly todo list application, isn’t that an ugly-looking application. well, you can add a quick styling with bootstrap rails gem.

let’s rollback and start over. wait, start over ? yeah I said it. Rails can rollback without any issues but you have to do it in the current order.

Rails database rollback

First, let’s start with the database, we need to delete the table we have created. use the following command:

rake db:rollback

Congrats, the todo list table has been deleted.

Destroy Rails Scaffold

Next, delete the files that our scaffold created:

rails d scaffold List

or

rails destory scaffold List 

done, we are back to zero.

Installing Rails Gems

okay, let add our styling so our simple todo list app looks sexy.

First, we need to add Rails gems if you still remember what is gems rails gems do. okay, we already talk about gems in getting to know Ruby on Rails.

To add rails gems we have to open the gems file, you will find it the root directory of your application. “Gemfile”

you can add the following gems to the end of the file

gem 'jquery-rails'
gem 'bootstrap-generators', '~> 3.3.4'
gem 'record_tag_helper', '~> 1.0'

save the file and go back to the terminal/command line and type the following command to install the gems for your rails application

bundle i 

or

bundle install

Adding Bootstrap templates

After the gems bundle is installed, you need to replace the default scaffold view template to the bootstrap view templates. todo so you can run the following command:

rails generate bootstrap:install

the terminal might ask you if you want to replace some files, you can just type yes then press enter. once you done running the command you are ready to create a sexy looking todo list application.

Generating Rails scaffold

well, we have done this already,

In the terminal, you can use this first command to create a scaffold:

rails g scaffold List title:string done:boolean

or

rails generate scaffold List title:string done:boolean

Database Migration

then run the following code to create the database table for the list

rake db:migrate

and yes that is it you have created your sexy todo list application using rails.

Start Rails server

run the server and look at that

rails s

or

rails server

what a great looking todo list app, in few mins without writing a single line of code.

Great, it is a Wrap!

That is great, you have reached the end of this article. well done. so we have covered the following topic

  • A quick history about ruby on rails
  • Pointing out the good and bad about ruby on rails
  • Preparing Rails development environment
  • Created our first Rails app.
  • Rails rollback process
  • And the process of Rails gems installation

At the end of the day, Rails is a strong framework and learning it will ensure greater success in your career.

You can find the code for this article in GitHub

Serve Keras Model with Flask REST API

Serve Keras Model with Flask REST API

This tutorial will briefly discuss the benefits of serving a trained Machine Learning Model with an API. Then we will take a look at a precise example using a Keras Model and Python Flask to serve the model. You’ll learn how to Serve Keras Model with Flask REST API.

Why serve ML Model with API?

Flexibility

Encapsulation the execution and manipulation of your machine learning model with an API has a few benefits. Of the benefit is the abstraction layer that you create with an (REST) API. This abstraction layer enables you to

  • test your application more easily (with tools that can send API Requests but cannot import your Tensorflow/PyTorch model directly
  • develop your application (you can initiate an execution with a REST Plugin, with your Browser or in CLI with curl
  • share functionality as a service (by deploying and making accessible via HTTPS; deploying it as a micro-service)

Mobility

Since your Model now be tweaked with pure HTTP Requests, you can deploy your Model and access/manage it via Requests. No need to login into the SSH to change a cronjob, to change a limit of SQL Query or initiate a new build to deploy a newer version.

Also, with REST API you can deploy your model easily to services like AWS ElasticBeanstalk, Google AppEngine, etc. They all need a working Server in order to deploy your app. And now you can call your Model an Application, because in fact, it is.

Serving Keras Model with Flask

The following Application Structure and Code are just one of the many possibilities how tackle this idea. If you don’t like it, you can check out the CookieCutter Template for more structure and MetaFlow for a whole complete framework.

Folder Structure

We need following folders to encapsulate the scripts, classes etc.

In the screenshot below you can see that we have a folder with different models (model_x.py). We need this separation because you could have multiple Machine Learning Models that need to be served by the same Flask Server. Optionally you can create a ML Model Loader Class that will create Machine Learning Model based a configuration file (e.g saved in yaml, json or database).

Minimal Folder Structure for a ML Model serving Application in Python.

In the queries folder you store your (in most cases very long) SQL Queries. You replace certain options with {parameter_x}, e.g: LIMIT {limit}. This way you’ll be able to dynamically generate parameterized SQL Queries reading the .sql File:

sql_file.read().format(limit=10000)

Tests/ are for tests. We are going to skip this due to scope.

Config.py is for Configurations (SQL Creds, Server Envs, etc.). We are going to skip this due to scope.

Server.py is for Flask serving our Services.

Our Services do certain actions with our model. For example: “train_service” would initiate a training process for a certain model. “prediction_service” would initiate a prediction process for a model and so on.

Machine Learning Model Class

In the code section below you can see a simple DynamicModel class with only one method which return the the compiled Keras Model. This Model does not have to be static and can be outsourced into a “build_model()” method or similar. Also, all the parameters in the layers like the input_shape should be set via the method parameters from model(). Since this is only an introductory tutorial, many useful methods are missing in this class.

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import keras

"""
Author: Andrey Bulezyuk @ German IT Academy (git-academy.com)
Date: 18.01.2020
"""

class DynamicModel():
    def __init__(self, model_name = None):
        self.model_name = model_name 

    def model(self):
        model = Sequential()
        model.add(Conv2D(32, (5, 5), input_shape=(28, 28, 1), activation='relu'))
        model.add(MaxPooling2D())
        model.add(Dropout(0.2))
        model.add(Flatten())
        model.add(Dense(128, activation='relu'))
        model.add(Dense(10, activation='softmax'))

        model.compile(loss=keras.losses.categorical_crossentropy,
                    optimizer=keras.optimizers.Adadelta(),
                    metrics=['accuracy'])
        return model
        

Service Layer

Why do we need a service layer between Flask API (server.py) and the Machine Learning Model (dynamic_model.py)? Simple. By having this extra layer (service.py) you can execute the services (in our case Class Methods) not only via REST API, but also from within other python modules.

Our service layer is responsible for importing the DynamicModel Class, loading and saving the trained model for prediction or training respectively.

import sys, os, datetime
sys.path.insert(1, os.path.join(os.getcwd(), "src/models"))
from dynamic_model import DynamicModel
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import load_model

"""
Author: Andrey Bulezyuk @ German IT Academy (https://git-academy.com)
Date: 18.01.2020
"""

class Service():

    # model_name must be supplied. 
    # otherwise no configuration cad be loaded.
    def __init__(self, model_name=None):
        self.model_name = model_name
        self.dynamic_model = DynamicModel(self.model_name)

    def _get_train_data(self):
        (x_train, y_train), (x_test, y_test) = mnist.load_data()
        # reshape to be [samples][width][height][channels]
        x_train = x_train.reshape((x_train.shape[0], 28, 28, 1)).astype('float32')
        x_test = x_test.reshape((x_test.shape[0], 28, 28, 1)).astype('float32')
        
        y_train = np_utils.to_categorical(y_train)
        y_test = np_utils.to_categorical(y_test)

        self.x_train = x_train
        self.x_test = x_test

        self.y_train = y_train
        self.y_test = y_test

    def train(self):
        # Load data
        self._get_train_data()

        # This return the compiled Keras Model from dynamic_model->model()
        print(self.y_train)
        model = self.dynamic_model.model()
        model.fit(self.x_train, self.y_train,
            batch_size=1000,
            epochs=4,
            verbose=1) 

        # Save trained model
        now = datetime.datetime.now()
        model.save(f"src/models/{self.model_name}_{now.year}{now.month}{now.day}_{now.hour}{now.minute}.h5")
        return True


    def predict(self, X):
        # Load model
        model = self._load_model()
        
        # Execute
        results = model.predict(X)
        if results is not None and results != False:
            return results
        return False

The train method works perfectly fine. You can see this in the section below when we execute it via Flask REST API with curl. The predict service method is not functional yet. The code and explanation for this is outside of the scope of this tutorial. Keep checking our IT Course Shop for similar courses with more in-depth material.

Flask API Server

Our server part is pretty simple. We import flask and our Service class. We create a route called ‘service’ with two parameters: service_name (which can be train, predict, stop, status, history, …) and model_name. Based on the parameters we execute the specified service.

import sys, os, json
sys.path.insert(1, os.getcwd())
sys.path.insert(1, os.path.join(os.getcwd(), "src"))
from flask import Flask, request
from service import Service

"""
Author: Andrey Bulezyuk @ German IT Academy (https://git-academy.com)
Date: 18.01.2020
"""

application = Flask(__name__)

@application.route("/")
def hello():
    return "Hello World!"


@application.route("/<string:service_name>/<string:model_name>", methods=["GET", "POST"])
def service(service_name=None, model_name=None):
    service = Service(model_name=model_name)

    # GET Request is enough to trigger a training process
    if service_name == 'train':
        service.train()
    # POST Request is required to get the X data for prediction process
    elif service_name == 'predict':
        service.predict()

    return f"Service: {service_name}. Model: {model_name}. Success."

if __name__ == "__main__":
    application.run(debug=True)

Example CLI & GET REquest

C:\Users\andre\code\servekeraswithapi>curl localhost:5000/train/ModelA
Service: train. Model: ModelA. Success.
Epoch 1/4
60000/60000 [==============================] - 8s 141us/step - loss: 6.5852 - accuracy: 0.7280
Epoch 2/4
60000/60000 [==============================] - 8s 140us/step - loss: 0.3276 - accuracy: 0.9141
Epoch 3/4
60000/60000 [==============================] - 8s 140us/step - loss: 0.1897 - accuracy: 0.9495
Epoch 4/4
60000/60000 [==============================] - 8s 140us/step - loss: 0.1256 - accuracy: 0.9645
127.0.0.1 - - [18/Jan/2020 20:54:53] "GET /train/ModelA HTTP/1.1" 200 -

That’s it with our short tutorial. If you liked it, subscribe to our Newsletter for more Tutorials. If you have any Questions feel free to contact us or leave a comment.

Getting started with PHP 7 in 2020

Getting started with PHP 7 in 2020

What is PHP?

PHP stands for Hypertext Preprocessor (earlier called “Personal home page”). It is an open source scripting language created for the web development. PHP is a server-side language which means all the code is rendered on server and only static HTML, CSS and JavaScript is sent to the client’s browser. PHP is a back-end language which means no one on client side can check the code written in PHP, only the person with authority to access the server can check the source code. Now let’s explore reasons to learn PHP 7 in 2020 and what lies ahead for this simple and beautiful language.

Why should I learn PHP 7 in 2020?

PHP is compatible with all leading operating systems such as Windows, Linux, MAC OS and many others. Likewise, it is compatible with all popular web servers such as Apache, NGINXm IIS etc. PHP7 offers great compatibility and performance. Not only is it open source but also it contains many features and it is absolutely easy to install and set-up. We will cover installation part later in this article.

What are features of PHP?

PHP comes with many benefits that let you create wonderful web applications.

1. Open Source

PHP is an open source programming language which means it is free to use. There is a great community to help you if you get stuck anywhere and not able to figure out the problem.

2. Cross-Platform

PHP supports all major operating systems and servers.

3. Easy to use

PHP is simple and clean scripting language. Its syntax is convenient to use. Anyone can quickly learn PHP.

4. Performance

It is one of the fastest programming language. It takes so little time to establish a connection with database or fetch data from web services.

How to install PHP7?

You can follow this guide to install PHP7 in your preferred operating system.

Windows :

Step 1 – Download PHP7

Go to the official PHP website and download the latest version. Save it on your windows PC.

Figure 1

Step 2 – Extract the zip

Figure 2

Step 3 – Setting up Environment variable

We need to configure the environment variable to access PHP from the command line. You can follow these steps to do so.

Right click -> My Computer (This PC) -> Properties -> Advanced system settings

This will open a the following window.

Figure 3

Now click on Environment variables, select path under the System variables section and edit. Add the path of installed PHP to system path.

Click on the new button and add the path to the PHP bin. Save all changes and close all the windows. Now to verify the settings, open console (or CMD) and execute following.

FIgure 4

If you get the following output, it means PHP is successfully installed on Windows.

Linux:

Here, we will see the steps to install PHP in Ubuntu Linux.

Step 1 – Update Ubuntu

Before installing anything new, you should always update your system. Open a terminal and run the following commands:

apt-get upgrade && apt-get update

Step 2 – Install PHP7

You can install PHP7 from Ubuntu’s official repository by following command:

apt-get install php

This command will install PHP7 and it’s required dependencies. To check whether PHP is installed or not execute following command:

php -v

It will return the PHP version related information.

PHP7 Syntax Overview

Like any other programming language PHP has a set of syntax rules which we need to follow while programming. PHP files commonly have a .php file extension as they’re always executed on server.

Tags in PHP or Escaping to PHP

The PHP parsing engine needs a way to differentiate PHP code from other elements. PHP tags are used for this.

We can ‘Escape to PHP’ by using the following 4 methods:

  1. Canonical PHP tags
  2. SGML (or) Short HTML Tags
  3. HTML Script Tags
  4. ASP Style Tags

From all of the above, Canonical PHP tags are most commonly used and are compatible with majority of servers.

Example:

<?php
    # Here the echo command prints the message
    echo "Hello world";
?>
Comments in PHP

Comments are statements in a program by developers which describe the intent and purpose of the code. There are 2 styles for comments in PHP. Comments in PHP code are not read or executed by the PHP engine. Therefore, they do not affect the output.

Single Line Comment

<?php
// This is a single line comment

echo "Hello World";

# This is also a single line comment
?>

Multi line Comment

<?php
/* 
Example for multiline comment
This is a multiline comment
*/

echo "Hello world";
?>
PHP Syntax is Case-Sensitive

In PHP besides variables, all other keywords are not case-sensitives. We have to be very careful while defining and using variables. Look at this example.

<?php
// Here all echo statements will execute
// in the same manner because keywords are case-insensitive

$variable = "Test";
ECHO $variable;

// You will get an "Undefined Variable" error
// Because variable names are case-sensitives

echo $VARIABLE;
?>

If you want to build a fast and beautiful Frontend for you PHP-Backend Application, consider the popular Framework Vue.JS 2 Course.

PHP Data types & Variables

Data Types

A Data type is the classification of data into a category according to its attributes. There are 4 major data types in PHP.

  • Integer – eg. 1, 1000, -12
  • Float – eg. 3.14
  • String – eg. “Test String”
  • Boolean – eg. True or False
Variables

A variable is a name given to a memory location that stores data at runtime. There are 2 types of variables, Global variables and Local variables. There are some pre-defined rules to create variables.

  • All variable names must start with the dollar sign. – eg. $testVariable
  • Variable names are case sensitive.
  • All variable names must start with a character.
  • Variable names must not contain any whitespaces between them.

PHP Control Structure – If else

If else is the simplest control structure. And it is relatively easy to understand even in PHP 7 in 2020. It evaluates the conditions using Boolean logic. Take a look at the following code snippet:

<?php
if (condition is true) {
   // Code block one
}else {
   // Code block two
}
?>

Here,

  • “(condition is true)” is the control structure, if it evaluates to true, “Code Block one” will be executed
  • If condition evaluates to false, “Code block two” will be executed.
  • In any situation only one of the following blocks will be executed.
<?php

// If else example

$x = 10;
$y = 20;

if($x > $y) {
    
    echo "$x is greater than $y";

} else {

    echo "$y is greater than $x";

}

// Output: 20 is greater than 10

?>

PHP Loops

While Loop

The while loop is use to execute a block of code repeatedly until the codition gets statisfied.

<?php

while (condition) {
    // Code to execute
}

?>

Here,

  • Code inside of while loop will be executes until the given “condition” is true.
<?php

$i = 0;

while ($i < 5) {
    echo $i;
    $i++;
}

/*
Output:

0
1
2
3
4

*/

?>
For Loop

For loop executes the block of code a specified number of times.

<?php

To (initialization; condition; increment/decrement) {

    // Code to be executed

}

?>

Here,

  • “initialize” is used to set the counter’s initial value.
  • “condition” is the condition that is evaluated for each loop iteration.
  • “increment/decrement” is used to increment or decrement the counter.
<?php

for ($i = 0; $i < 5; $i++) {
    echo $i;
}

/*
Output:
0
1
2
3
4
*/

?>
ForEach Loop

The php foreach loop is used to iterate through array values.

<?php

foreach($array_variable  as $array_value){

    //Code block to be executed

}

?>

Here,

  • $array_variable is the array variable to be looped through.
  • $array_value is the temporary variable that holds the current array item.
<?php

$arr = [1, 2, 3, 4, 5]

foreach ($arr as $item) {
    echo $item;
}

/*
Output:
1
2
3
4
5
*/

?>

Executing PHP File

There are two ways to execute PHP files.

  1. Executing PHP file in browser
  2. Executing PHP file in terminal (command line)
Executing PHP file in browser

Step 1: Create your PHP file in www or htdocs folder of your server.

Step 2: Turn on your server.

Step 3: Go to http://localhost/<file_name>

Figure 5
Executing PHP file from terminal (command line)

Step 1: Open your preferred terminal

Step 2: Navigate to your file location (directory)

Step 3: Execute the file by following command

php <filename.php>
Figure 6

As you can see, it will one of the best skills you could acquire for yourself and your resume. We are certain that PHP 7 in 2020, will have a continuously growing community.

How to Run Moodle with Docker Compose

How to Run Moodle with Docker Compose

In this tutorial we are going to have a Moodle Instance up and running on a Virtual Machine – inside Docker Containers.

First of all, install and get Docker up and running. Then, download Moodle or make sure you have a Git-Repository ready at hand. We are going to use docker-compose for this task. Now let’s try and Run Moodle with Docker.

Moodle with Docker

We need a container that will have all the needed technology to run and serve the Moodle source code (your repository). This configuration will come from an Image, that we will use and configure through a docker-compose.yml file. Create a file docker-compose.yml and insert the version of docker-compose syntax that we are going to use:

version: "3.3"

These Technologies are needed:

  • Moodle Container
    • Operating System (Ubuntu)
    • Server (Apache2, Nginx)
    • PHP7.x (incl. php-curl, php-mysql, etc.)
  • Database Container
    • MariaDB 10+

Database Docker Image

We are going to use a simple and straightforward solution from bitnami. We simple create a service that will use this image, and set some parameters like username, db_name, etc.

services:
  mariadb:
    image: "bitnami/mariadb:10.1"
    networks:
      - moodle-net
    environment:
      - MARIADB_USER=bn_moodle
      - MARIADB_DATABASE=bitnami_moodle
      - ALLOW_EMPTY_PASSWORD=yes
    volumes:
      - type: bind
        source: /home/maria_data
        target: /bitnami
    ports:
      - "3306:3306"

We call our service ‘mariadb’, expose some ports (3306) and bind a volume to persist our data on our host machine. We also attach ‘mariadb’ to a network moodle-net.

Andrey Bulezyuk

German IT Academy Coach

Andrey Bulezyuk is the founder of German IT Academy and a course creator. He mainly covers topics from Web Development (NodeJS, VueJS, Django etc.) to Data Science (Pandas, Numpy) and Machine Learning (Tensorflow, Keras, etc.). He published a German book “Algorithmic Trading“, giving his readers the opportunity to learn how to code automatic trading systems for the stock market or the Forex. He has experience as a Backend and Frontend Developer. In his early years he worked on Web Projects as a Freelancer. Switched later to Financial Market System Developing. Currently employed as Machine Learning Engineer. He takes part in different projects and acts as a Co-Founder in different small start-ups. Andrey Bulezyuk was an employed Full-Stack Developer in Munich. Currently his duties do cover areas of Machine Learning and ETL.