Prinsip MVC untuk Pengaturcara PHP

Apakah itu MVC?

MVC adalah singkatan daripada Model-View-Controller (MVC). Ia adalah satu seni bina perisian (software architecture) atau corak reka bentuk (design pattern) yang digunakan secara meluas dalam pembangunan laman web. Ia biasanya digunakan untuk mencipta aplikasi web atau perisian dengan lebih cekap atau efisyen. Pada topik kali ini, perbincangan MVC adalah dalam skop bahasa pengaturcaraan PHP; satu bahasa pengaturcaraan yang banyak membangunkan framework berkonsepkan MVC, selain daripada ASP.NET, Ruby on Rails dan Zend Framework.

Ketiga-tiga modul utama diterapkan dalam pembangunan web PHP yang mengakibatkan pembangunan aplikasi web berskala dan menarik.

Mengapa anda harus menggunakannya?

Untuk pengaturcara PHP, MVC menawarkan konsep dan idea yang kreatif dan lebih baik berbanding procedural PHP. Pada asasnya, struktur MVC yang menyediakan susunan kod atau fungsi dalam bentuk yang mudah serta dapat menambah fungsi baru dengan lebih efisyen untuk penyesuaian atau penggunaan semula kod agar pembangunan aplikasi menjadi lebih cepat.

MVC membantu pengaturcara PHP menguruskan pembangunan aplikasi web dengan lebih konsisten dan mudah. Melalui MVC juga, anda boleh memisahkan antara logik pengaturcaraan (programming logic) dan kod antara muka (interface code).

Keperluan MVC framework bagi pengaturcara PHP

Dengan menggunakan MVC Framework, pengaturcara PHP dapat membangunkan, menguruskan, menyelenggara dan memastikan prestasi aplikasi web yang dibangunkan dengan lebih mudah, tersusun dan cekap. Terdapat berbagai PHP MVC Framework yang telah dibangunkan seperti Laravel, CakePHP, CodeIgniter, Yii, FuelPHP, Symfony, Kohana, Zend Framework dan sebagainya. Setiap framework mempunyai kelebihan dan kekurangannya tersendiri.

Kebaikan MVC framework

MVC memudahkan anda untuk dalam menaiktaraf dan menyelenggara aplikasi web anda. Selain itu, MVC framework juga mempunyai pengurusan modules yang teratur dan cekap bagi memudahkan pembangunan aplikasi web yang besar. Ia juga memudahkan pengaturcara baru dilantik untuk menyelenggara aplikasi web yang telah dibangunkan menggunakan MVC tersebut. Mereka yang menggunakan struktur dan logik MVC semasa membangunkan aplikasi juga akan mendapati untuk menambah fungsi baru atau menggunakan semula kod-kod yang telah dibuat adalah lebih cepat dan tersusun; terutama bagi mereka yang membangunkan aplikasi web secara berkumpulan. Dengan menggunakan MVC framework, aplikasi web dapat dihasilkan dengan cepat dan seterusnya akan menjimatkan masa pembangunan dan penyelenggaraan.

Struktur fail MVC

MVC framework menawarkan struktur fail dengan paling mudah untuk dipelajari, dipahami dan digunakan seperti View untuk paparan, Model untuk pengurusan pengkalan data Controller sebagai penghubung antara kehendak pengguna (user request) dan paparan yang ingin dilihat. Setiap struktur ini berkait antara satu sama lain. Terdapat juga folder-folder lain di dalam MVC framework yang digunakan sesuai dengan keperluan dan fungsi framework itu sendiri.

Sumber: Codelution.com

 

JomLaunch 2015

Acara yang saya nantikan oleh JomWeb untuk tahun ini bermula pada @ 04 April, 2014 @ 09:00 lagi. Program ini adalah idea yang dicetuskan oleh saudara Nazrol Hazif bersama-sama dengan Komuniti JomWeb untuk membolehkan ahli-ahli jomweb yang telah menyiapkan @ merancang aplikasi mereka membentang projek yang mereka telah/sedang bangunkan. Pelbagai syarikat dan individu melancarkan aplikasi mereka.

Posto Express

a

Sistem ala transporter dimana pengirim barang akan menghantar barangan kepada pembeli melalui penghantar yang dilantik oleh Posto Express sendiri. Setiap barangan yang dihantar akan dicaj RM0.90 bagi setiap KM. Melalui sistem ini, pengirim dan penerima dapat memantau progres dan pergerakan barangan yang dihantar melalui GPS Location (menggunakan google map). Bagi anda yang berminat untuk menjadi penghantar barangan secara part-time @ full-time. Penghantar akan menerima bayaran sebanyak RM10.00 (minima) bagi setiap barangan yang berjaya dihantar.

Pong Flashback – Android Game

a

Satu penghormatan kepada permainan pong (game android) klasik oleh Mikhail Game Tech. App ini dibina untuk acara JomLaunch bagi kumpulan JomWeb untuk pemaju dan pengaturcara Malaysia.

MaidEasy

a

Projek ini dibentangkan oleh saudara Azrul Rahim. Bagi anda yang ingin mendapatkan khidmat pembantu rumah dengan cepat dan pantas, sila layari web MaidEasy.My

PekanBanting

a

Projek keempat yang dikongsikan adalah laman perkongsian yang khusus untuk pekan Banting di Selangor. Projek GPS Social Network ini dicipta untuk menggalakkan perkongsian maklumat, dan membolehkan pengguna bersembang dan juga mengetahui lokasi-lokasi disekitar Banting. Pemilik perniagaan disekitar Banting juga boleh mengiklan di halaman ini.

CastMyCode

a

Saudara Zulfa Juniadi yang saya kenal memang seorang yang kreatif untuk menghasilkan projek-projek yang bernas. Untuk sesi kali ini beliau membentangkan projek CastMyCode. melalui aplikasi ini, pelajar dapat mengikut/menyalin kod-kod pengaturcaraan yang dibuat oleh pengajar dengan mudah dan dengan jelas secara ‘live’. Insyallah, saya akan gunakan aplikasi ini pada kursus akan datang. Buat masa ini sesi yang disediakan akan lupus selepas seminggu.

Engine Scheduler

a

Sekiranya anda menghadapi masalah kekangan waktu untuk membuat servis kereta. Engine Scheduler adalah satu aplikasi mudah untuk anda menentukan jadual agar kereta anda boleh diservis pada waktu yang ditetapkan.

Alambiz Malaysia

a

Satu portal membeli-belah dalam talian yang menawarkan pelbagai produk halal. Ahli yang berdaftar mendapat kelebihan harga diskaun sebanyak 10% dan rebat yang berpatutan.

MudahUrus.My

a

Sistem Pengurusan Tempahan Secara Online. Dengan Mudahurus.my, pembangunnya menyediakan sistem pengurusan dimana peniaga boleh mendaftar dan mewujudkan borang tempahan dengan mudah. Kesemua pembelian akan direkodkan dan terdapat kemudahan kod penjejak (Trackback) untuk pengeposan Pos Malaysia. Buat masa ini projek ini masih ditahap percubaan namun bagi peniaga yang ingin mendaftar minat boleh melawati halaman mereka.

SewaPandu

a

Pembangun ini menghadapi masalah perlu membuka sejumlah halaman untuk membandingkan kereta sewa yang diinginkan. Projek Sewapandu boleh dikatakan penyewaan kereta berasaskan AirBNB, membolehkan pemilik kenderaan menyewakan kenderaan mereka kepada pengguna lain. Menariknya selain dari melihat maklumat berkenaan kereta, pengguna juga boleh melihat rekod selenggara kereta sewa tersebut, sekaligus menjamin keselamatannya. Projek ini masih di peringkat Beta dan akan dilancarkan tidak lama lagi.

Nexmo Dashboard

a

Satu Dashboard untuk memudahkan pelanggan Nexmo menguruskan SMS Nexmo mereka. Ia dibangunkan oleh saudara Mohd Sulaiman.

Go Tickets

a

Pembelian tiket secara atas talian untuk tempat-tempat menarik di Malaysia

Unimall.my

a

Satu portal untuk jual-beli khusus untuk pelajar IPT.

DNS Vault

a

Slogan mereka ‘DNS Management Made Easy’. Pembentangan oleh otai Localhost Sdn Bhd iaitu saudara Amir Haris.

MyOfis

Satu lagi aplikasi ‘All-in-one office information system’. Pembentangan juga oleh saudara Amir Haris.

SimpanKira

a

SimpanKira.com adalah perisian perakaunan yang mematuhi kehendak GST yang dapat memenuhi keperluan sama ada perniagaan kecil mahupun sederhana di Malaysia. Ia akan membantu anda, pemilik perniagaan untuk lebih memberi tumpuan kepada perniagaan anda.

WikiMesjid

a

Satu aplikasi mobile untuk mencari masjid yang terdekat atau kedai halal yang berhampiran di lokasi anda dengan cepat dan mudah.

Trainer.my

a

Trainer.My adalah satu portal untuk memudahkan kita mendapatkan tenaga pengajar sesuai dengan kepakaran yang diperlukan. Dibangunkan oleh saudara Nazrul Hazhan Nazlan (juga membangunkan AlQurah.My).

Baby.My

Aplikasi ini juga dibangunkan oleh saudara Nazrul Hazhan Nazlan untuk memudahkan kita menjual / membeli / ‘menyedekahkan’ peralatan / pakaian bayi kita.

a

Program JomLaunch ini berjalan dengan lancar sekali dan berakhir pada jam 02:00 petang. Saya mengucapkan sebanyak tahniah kepada penganjur (training.my) dan komuniti JomWeb serta tidak lupa juga kepada pihak sponsor yang telah sudi menjadi sponsor agar program berjalan dengan lancar dan baik. Sesi akhir… makan tengahari. Hopefully penganjur boleh buat sesi bergambar untuk program akan datang.

Sumber: Amanz.My, Gambar drp Album Jomweb saudara Jasdy Syarman dan saudara Iszuddin Ismail

PHP PDO Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

PARAM

PDO::PARAM_BOOL (integer) – Represents a boolean data type.
PDO::PARAM_NULL (integer) – Represents the SQL NULL data type.
PDO::PARAM_INT (integer) – Represents the SQL INTEGER data type.
PDO::PARAM_STR (integer) – Represents the SQL CHAR, VARCHAR, or other string data type.
PDO::PARAM_LOB (integer) – Represents the SQL large object data type.
PDO::PARAM_STMT (integer) – Represents a recordset type. Not currently supported by any drivers.
PDO::PARAM_INPUT_OUTPUT (integer) – Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.

FETCH

PDO::FETCH_LAZY (integer) – Specifies that the fetch method shall return each row as an object with variable names that correspond to the column names returned in the result set.
PDO::FETCH_LAZY – creates the object variable names as they are accessed. Not valid inside PDOStatement::fetchAll().
PDO::FETCH_ASSOC (integer) – Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_ASSOC returns only a single value per column name.
PDO::FETCH_NAMED (integer) – Specifies that the fetch method shall return each row as an array indexed by column name as returned in the corresponding result set. If the result set contains multiple columns with the same name, PDO::FETCH_NAMED returns an array of values per column name.
PDO::FETCH_NUM (integer) – Specifies that the fetch method shall return each row as an array indexed by column number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_BOTH (integer) – Specifies that the fetch method shall return each row as an array indexed by both column name and number as returned in the corresponding result set, starting at column 0.
PDO::FETCH_OBJ (integer) – Specifies that the fetch method shall return each row as an object with property names that correspond to the column names returned in the result set.
PDO::FETCH_BOUND (integer) – Specifies that the fetch method shall return TRUE and assign the values of the columns in the result set to the PHP variables to which they were bound with the PDOStatement::bindParam() or PDOStatement::bindColumn() methods.
PDO::FETCH_COLUMN (integer) – Specifies that the fetch method shall return only a single requested column from the next row in the result set.
PDO::FETCH_CLASS (integer) – Specifies that the fetch method shall return a new instance of the requested class, mapping the columns to named properties in the class. Note: The magic __set() method is called if the property doesn’t exist in the requested class
PDO::FETCH_INTO (integer) – Specifies that the fetch method shall update an existing instance of the requested class, mapping the columns to named properties in the class.
PDO::FETCH_FUNC (integer) – Allows completely customize the way data is treated on the fly (only valid inside PDOStatement::fetchAll()).
PDO::FETCH_GROUP (integer) – Group return by values. Usually combined with PDO::FETCH_COLUMN or PDO::FETCH_KEY_PAIR.
PDO::FETCH_UNIQUE (integer) – Fetch only the unique values.
PDO::FETCH_KEY_PAIR (integer) – Fetch a two-column result into an array where the first column is a key and the second column is the value. Available since PHP 5.2.3.
PDO::FETCH_CLASSTYPE (integer) – Determine the class name from the value of first column.
PDO::FETCH_SERIALIZE (integer) – As PDO::FETCH_INTO but object is provided as a serialized string. Available since PHP 5.1.0. Since PHP 5.3.0 the class constructor is never called if this flag is set.
PDO::FETCH_PROPS_LATE (integer) – Call the constructor before setting properties. Available since PHP 5.2.0.

ATTR

PDO::ATTR_AUTOCOMMIT (integer) – If this value is FALSE, PDO attempts to disable autocommit so that the connection begins a transaction.
PDO::ATTR_PREFETCH (integer) – Setting the prefetch size allows you to balance speed against memory usage for your application. Not all database/driver combinations support setting of the prefetch size. A larger prefetch size results in increased performance at the cost of higher memory usage.
PDO::ATTR_TIMEOUT (integer) – Sets the timeout value in seconds for communications with the database.
PDO::ATTR_ERRMODE (integer) – See the Errors and error handling section for more information about this attribute.
PDO::ATTR_SERVER_VERSION (integer) – This is a read only attribute; it will return information about the version of the database server to which PDO is connected.
PDO::ATTR_CLIENT_VERSION (integer) – This is a read only attribute; it will return information about the version of the client libraries that the PDO driver is using.
PDO::ATTR_SERVER_INFO (integer) – This is a read only attribute; it will return some meta information about the database server to which PDO is connected.
PDO::ATTR_CONNECTION_STATUS (integer)
PDO::ATTR_CASE (integer) – Force column names to a specific case specified by the PDO::CASE_* constants.
PDO::ATTR_CURSOR_NAME (integer) – Get or set the name to use for a cursor. Most useful when using scrollable cursors and positioned updates.
PDO::ATTR_CURSOR (integer) – Selects the cursor type. PDO currently supports either PDO::CURSOR_FWDONLY and PDO::CURSOR_SCROLL. Stick withPDO::CURSOR_FWDONLY unless you know that you need a scrollable cursor.
PDO::ATTR_DRIVER_NAME (string) – Returns the name of the driver.
PDO::ATTR_ORACLE_NULLS (integer) – Convert empty strings to SQL NULL values on data fetches.
PDO::ATTR_PERSISTENT (integer) – Request a persistent connection, rather than creating a new connection. See Connections and Connection management for more information on this attribute.
PDO::ATTR_STATEMENT_CLASS (integer)
PDO::ATTR_FETCH_CATALOG_NAMES (integer) – Prepend the containing catalog name to each column name returned in the result set. The catalog name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
PDO::ATTR_FETCH_TABLE_NAMES (integer) – Prepend the containing table name to each column name returned in the result set. The table name and column name are separated by a decimal (.) character. Support of this attribute is at the driver level; it may not be supported by your driver.
PDO::ATTR_STRINGIFY_FETCHES (integer)
PDO::ATTR_MAX_COLUMN_LEN (integer)
PDO::ATTR_DEFAULT_FETCH_MODE (integer) – Available since PHP 5.2.0
PDO::ATTR_EMULATE_PREPARES (integer) – Available since PHP 5.1.3.

ERRMODE

PDO::ERRMODE_SILENT (integer) – Do not raise an error or exception if an error occurs. The developer is expected to explicitly check for errors. This is the default mode. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_WARNING (integer) – Issue a PHP E_WARNING message if an error occurs. See Errors and error handling for more information about this attribute.
PDO::ERRMODE_EXCEPTION (integer) – Throw a PDOException if an error occurs. See Errors and error handling for more information about this attribute.
PDO::ERR_NONE (string) – Corresponds to SQLSTATE ‘00000’, meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.

CASE

PDO::CASE_NATURAL (integer) – Leave column names as returned by the database driver.
PDO::CASE_LOWER (integer) – Force column names to lower case.
PDO::CASE_UPPER (integer) – Force column names to upper case.

Sumber: PHP.Net

Ubuntu 14.04 on VirtualBox

Alhamdulillah. Cuti yang banyak pada bulan Februari ini memberi peluang untuk menambahkan lagi ilmu mengenai Sistem Operasi berasaskan Unix. Sistem Operasi Ubuntu Desktop 14.04 telah dipilih memandangkan ia lebih user friendly (ala-ala windows deskop). Memandangkan saya hanya ingin belajar untuk pemasangan dan penggunaan sistem operasi ini secara asas serta beberapa aplikasi lain yang terdapat dalam ubuntuk, jadi saya menggunakan VirtualBox sebagai tools untuk mencipta sistem operasi secara virtual.

Pemasangan Sistem Operasi Ubuntu Desktop 14.04 ini amat mudah. Terutama dengan tutorial yang sedia ada dalam Komuniti Ubuntu; sangat membantu. Tapi sebelum ini kita perlu memasang VirtualBox. Juga terdapat banyak tutorial pemasangan dan penetapan yang boleh digunakan semasa pemasangan. Untuk komputer saya dengan spesifikasi di bawah:

pc

 

Proses pemasangan tidak menjadi masalah besar. Cuma saya menghadkan sumber (ruang HDD dan RAM) agar penggunaannya tidak keterlaluan. Berikut setting yang telah ditetapkan setelah sistem operasi ini berjaya dipasang di virtualbox:

vbox

 

Setelah pemasangan sistem operasi berjaya. Perkara pertama bermain difikiran saya adalah bagaimana untuk memasang web server (LAMP – linux, apache2, mysql dan php) ke dalam ubuntu desktop ini. Dengan mengikut tutorial seperti video di youtube ini, akhirnya saya berjaya memasangan aplikasi apache, php, mysql, phpmyadmin dan wordpress. Melalui video ini juga saya belajar menetapkan pengguna dan permission untuk pengguna tadi. Satu yang saya tertarik dalam video ini adalah proses memasang Webmin.

Insyallah lepas ini, akan banyak lagi penerokaan pada Sistem Operasi Ubuntu Desktop 14.04 ini akan dilakukan.

Jom PDO

Memandangkan sekarang kita sudah mula menggunakan PHP dan kaedah PDO untuk berinteraksi dengan pengkalan data mySQL serta ada kawan-kawan yang bertanya mengenai PDO, jadi saya akan buat satu tutorial ringkas procedural PHP dan PDO untuk pengkalan data mySQL. Sebelum itu untum rujukan mengenai PDO, sila rujuk artikel MySQLi vs PDO.

Contoh kod sambungan ke pengkalan data:

<?php
try {
$conn = new PDO(‘mysql:host=localhost;dbname=datasaya’, “root”, “abc123”);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
}
catch(PDOException $e) {
die(‘ERROR: ‘ . $e->getMessage());
}
?>

Code di atas adalah untuk membuat sambungan ke pengkalan data mySQL dengan datasaya adalah nama pengkalan data, root adalah pengguna pengkalan data dan abc123 adalah katalaluan pengguna pengkalan data.

Contoh kod untuk tambah data:

<?php
$s = “INSERT INTO pengguna SET nama = :nama, katalaluan = :pass”;
$q = $conn->prepare($s);
$q->execute(array(
‘nama’ => $_POST[‘nama’],
‘pass’ => $_POST[‘pass’]
));
?>

Kod di atas akan menambah nilai yang dibawa melalui kaedah $_POST iaitu nama dan pass ke dalam pengkalan data.

Contoh kod untuk memilih data:

<?php
$s = “SELECT * FROM pengguna WHERE nama LIKE :nama”;
$q = $conn->prepare($s);
$q->execute(array(
‘nama’ => ‘%’.$_POST[‘nama’].’%’
));
?>

Kod di atas akan memilih data dimana field nama pengkalan datanya adalah yang berpadan dengan nilai yang dihantar melalui kaedah $_POST tersebut

Contoh kod untuk mengubah data:

<?php
$s = “UPDATE pengguna SET nama = :nama WHERE id = :id”;
$q = $conn->prepare($s);
$q->execute(array(
‘nama’ => $_POST[‘nama’],
‘id’ => $_POST[‘id’]
));
?>

Kod ini pula adalah untuk mengemaskini maklumat data kepada nilai nama yang baru untuk pengguna id berkenaan

Contoh kod untuk menghapus data:

<?php
$s = “DELETE FROM pengguna WHERE id = :id”;
$q = $conn->prepare($s);
$q->execute(array(
‘id’ => $_POST[‘id’]
));
?>

Dan kod ini pula adalah untuk menghapus data bagi id pengguna berkenaan

Jadi setakat ini dulu asas kepada pengaturcaraan PHP menggunakan kaedah PDO untuk berinteraksi dengan mySQL.

Currently and mission…

Maaf lama tidak menghantar tutorial! Jadi, apa yang saya sedang lakukan pada waktu ini?

1) Membangunkan Portal eLearning Psikiatri
2) Membangunkan Sistem MealPlan
3) Mengemaskini Portal Aktiviti
4) Mengajar PHP & mySQL : Basic to Intermediate (insyallah)

Dan masih terus menambah ilmu mengenai:

1) Laravel 4.2
2) Sublime Text 3
3) Git 1.9.4
4) PHP 5.5.15 (will upgade to 5.6 later)

Insyallah…

GIT – Distributed Version Control and Source Code Management (SCM) System

Introduction To GIT

  1. Abstract
  2. Creating a Repository
  3. Checking Out A Repository
  4. Add And Commit
  5. Pushing Changes
  6. Branches
  7. Update and Merge
  8. Tagging
  9. Revert To Specifit Commit

Abstract

GIT is a distributed version control and source code management (SCM) system developed by by Linus Torvalds for Linux kernel development, Git has since been adopted as the choice of source code management by many projects and companies. This document covers the creation, usage and management of the GIT versioning system.

The installation of GIT is beyond the scope of this tutorial, however, here are some links that will help

 

Creating a Repository

To create a repository for your project, select a place where you have write privileges. For our purposes here, we will create a repository for a project name ACL. So lets begin with creating the repository(repo).

mkdir ~/git_repos
mkdir ~/git_repos/acl
cd ~/git_repos/acl
git init

The above commands will firstly create a directory name .git in which, in turn, will contain some directories and files need to work with the GIT system. A quick look inside the .git directory shows us the following

# ls ~/git_repos/acl/.git
branches config description HEAD hooks info objects refs

Checking Out A Repostiory

If you are using a local repository, checking out a copy is as simple as:

git clone ~/git_repos/acl

If you are checking out a remote repository, then use this command.

git clone username@hostname:/home/kevin/git_repos/acl

The local repository consists of three “trees” maintained by git

Working Directory
Contains the acutal files
Index
Acts as a staging area
HEAD
Points to the last commit

The workflow will look like this.

WORKING DIR -> add -> INDEX -> commit -> HEAD

Add And Commit

When you add a file to GIT, the addition is stored as a proposed changed, which means it is stored in the Index. To add a file named acl.php is as simple as:

git add acl.php

If you had multiple files you wanted to add, you can use the command

git add *

Currently the file is just a proposed addition, and not commited to the repository. To commit we use git commit.

git commit -m “Message to say I added acl.php file”

The acl.php is now in HEAD, but not yet in the remote repository repository. Any additions and changes need to be pushed to the remote repository before they are available to all.

Pushing Changes

To push changes to the remote repository, the git push command is used.

git push origin master

The master can be whatever branch you want to push the changes to.

Thats IT!?. Yup, thats it

If you have not cloned an existing repository and want to connect your repository to a remote server, you need this command

git remote add origin server_name

Now you are able to push your changes to the selected remote server

Branches

Branches are used to develop features in isolation. The master branch is the “default” branch when you create a repository. Use other branches for development and merge them back to the master branch upon completion.

The workflow will look like this..

           ---------- Feature ----------
          |                            |
          |                            |
--------------------- Master -------------------------
       branch                        merge

So, to create a branch called my_feature_branch, and switch directly to it

git checkout -b my_feature_branch

You should see a message like

Switched to a new branch ‘my_feature_branch’

Now, to switch back to master brach

git checkout master
Switched to branch ‘master’

A local branch is not available to others, as it is not yet in the repository. The branch needs to be pushed to the remote repository to be available to all.

git push origin my_feature_branch

And finally, to delete the branch, we use the -d switch

git branch -d my_feature_branch
Deleted branch my_feature_branch (was b37035b).

Update and Merge

Of course, you are not the only person using the repository. Others will commit changes and you need to keep your local copy up to date by pulling new changes from the remote repository. To do so, use the pull command. This will both pull and merge changes from the remote repo, into your local copy.

git pull

To merge another branch into your active branch eg: master, use this command.

git merge my_feature_branch

When git pulls from the remote repository, or merges a branch, it tries to auto-merge the content. Inevitably, there are conflicts. You are responsible to merge those conflicts manually by editing the files shown by git. After changing, you need to mark them as merged. Using:

git add

Some of these conflicts can be avoided by checking for conflicts before merging with git diff

git diff source_branch target_branch

`

Tagging

Tagging a release is a great idea for tracking releases and milestones in a project. Those who are familiar with SVN would be familiar with this concept. To create a new tag, first use the git log command to get the last commit ID and then use git tag with the ID you just gained.

git log
commit b37035b424c82dd1b4baee3b8184ddbead32edd0
Author: Kevin Waterson <kevin@jyotish.(none)>
Date: Fri Jul 5 09:37:27 2013 +1000git tag 1.0.0 b37035b424c82dd1b4baee3b8184ddbead32edd0

Another simple way to use a an annotated tag in GIT, which is really just a pointer to the current commit is this. This example assumes a tag for a release of version 37 of a project.

git tag -a v37 -m ‘Release 37’

Revert To Specifit Commit

Sometimes you need to revert or rollback to a specific commit. Here we show how to revert back to commit id 296b09c

git reset 296b09c
git reset –soft HEAD@{1}
git commit -m “Revert message to tell you have reverted”
git reset –hard