Book Review: Full Stack Javascript by Azat Mardan

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

I got a book few months ago named “Full Stack JavaScript” by Azat Mardan, that I have read just now.  I also got a request for writing review of it. So here I want to share non-biased review which should be information for you guys to decide whether to read or not read this book.

 

Summary:

Full Stack JavaScript is a book not about JavaScript as a language. If you are interested in JavaScript as a language, then either read https://github.com/getify/You-Dont-Know-JS or my previous article Good Resources For Learning Javascript . It is about how to use JavaScript when your role is Full Stack JavaScript developer. It don’t say it in book but this is what I got from it. It go through different tools and frameworks you need to know or approach that you should use. It give introduction to numerous things. Not only tools but also cloud platforms which you can use to deploy your app. It also discuss agile methodologies.

Content of Book:

In first chapter, Azat discusses Agile methodologies and frontend and backend concepts and flow and introduces NodeJS and MongoDB as well.

In second chapter, you can learn that how to setup your environment. Your local environment, setup Git for deployment, Windows Azure and Heroku deployment related stuff setup, your SSH Keys generation and MongoDB installation and setup.

Third Chapter name is JQuery and Parse.com but it have lot of different things in it. Introduction to cross domain, AJAX and JSON. Then he introduced lot of stuff that is typically useful for frontend developers: JQuery functions, Twitter Bootstrap, LESS and then finally an example using Twitter API and JQuery. In same chapter, Parse.com is used for an example app and then deployment on Windows Azure and Heroku. So in short he tried to cover all those different things implementation in one chapter.

Fourth chapter is mostly related to Backbone.js and its loading using AMD and require.js etc. Good thing about this chapter was that writer tried to cover only one thing in this whole chapter. Then in Chapter 5, it was related to usage of Backbone JS in example he started for parse.com. Chapter 4 and 5 were better than previous chapters but unfortunately my intention wasn’t to learn backbone.js as I was more interested in Nodejs and MongoDB.

Chapter 6 and 7 were interesting for me as Chapter 6 is completely on Node JS and and Chapter 7 is completely on MongoDB.

In chapter 6, Azat explained NodeJS core modules and NPM and deployment on different could platforms. It was good to know NodeJS modules infromation but the key thing that he missed here was explainging Event Loop and flows. However, he showed usage with example, and introduced unit test for example code. Then instead of discussing how to test or what to test, he just provided a list of test frameworks.

Other interesting chapter is chaper 7 which is all about MongoDB. He told installation, configuration and usage of MongoDB.

Then in Chpater 8, writer just put everything together including examples of UI and API and deployment.

Pros and Cons and Opinion:

It is worth mentioning that everything discussed above in book is in no more that 208 pages. So it is good that you can get overview of all that stuff in 208 pages and it is bad because how much detail of so many things can be included in 208 pages? So it is good if you want to get overview of all that stuff in less time and in one book, but it is bad if you want to get detail of any of these things.

This book is more a list of articles introducing lot of different things and providing list of rest of stuff.

Writing Style:

Overall writing style of Azat Mardan is very good and code is well explained, however the way he structured chapters that is multiple things in one chapter, and one thing spanning over multiple chapters was little bit annoying.

So is this useful book for you?

It depends on who you are and what you want from this book. It is very good book for people who have JS language knowledge and aiming to be Full stack developer and want to immediately start learning different things Full Stack developer should know. But if you are like me, who already know about these things but want to get deeper look and wants to do development while taking occasionally opinion of writer, then it is not for you. Because this book gives overview of lot of stuff but does not get into depth of even one thing.

This is just my opinion after reading book, if you think anything different then feel free to discuss in comments below.

In case if you want to buy this book then you can buy it here: Full Stack JavaScript: Learn Backbone.js, Node.js and MongoDB

Good resources for learning Javascript

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

JavaScript is a widely used, amazing and misunderstood language by many developers. Its different concepts make it difficult for programmers coming from other languages. Here I am not going to explain different concepts but telling different resources learn JS (JavaScript).

Knowing basics of JS in browser (For Beginners):

If you are just a starter, who know some other language and want to quickly go through basics of Javascript, then quickest and basic way to do is to go through JS tutorials on W3Schools: http://www.w3schools.com/js/

Understanding JS Beyond Basics:

Although W3Schools is good for beginning JS, however if you want to understand beyond basics, then there are couple of good books written on JavasScript. So here are two books I recommend for Learning Javascript:

Eloquent JavaScript:

Eloquent JavaScript is very recommended book for almost every one trying to learn JavaScript as a language not just a way to do some basic things in browser (W3Schools is already there for that purpose). It is very well written and suitable for most of people. Although it is easy to start with but it is not just basic, it also contains significant detail. This book is not just about language only but also covers different concepts for new comers. So even if you are new to programming, this book is awesome choice. Get it from Amazon.

If you are not intending to buy Paperback and interested in free online reading or PDF edition then get that from here: http://eloquentjavascript.net/

Professional JavaScript for Web Developers:

This was the book from where I started understanding JavaScript. It is not just focused only on JavaScript as a language but also other things that you should know as a web developer. Also similar to Eloquent JavaScript, this book is easy to follow for beginners as well. Get it from Amazon.

Although I found these 2 books amazing for people who have basic JS knowledge but want to understand more, but there are many people who prefer videos instead of books, so in that case you can probably find something helpful on https://frontendmasters.com/, however for developers with basic JS knowledge who want to improve, my recommendation goes with above mentioned books.

Advanced JavaScript:

By Advanced JavaScript, I mean something that experienced developers are interested in. Due to JavaScript’s different nature, many experienced developers face trouble understanding JavaScript in depth.

JavaScript Good Parts:

When it comes to understanding Javascript in depth, then there is an awesome book “JavaScript the Good Parts” written by Douglas Crockford

This book is sort of must read, if JavaScript is something that you are going to do seriously in future. You can get it from Amazon.

If you don’t like reading books, then good news is that on Frontend masters, there are courses by Douglas Crockford named as “JavaScript the Good Parts” and “The Good Parts of JavaScript and the Web”, so you can watch them there as well, however I personally don’t think that whole book can be gathered in those video courses.

Advanced JavaScript by Kyle Simpson:

Another awesome advanced level video training course on Javascript is Advanced JavaScript by Kyle Simpson, available on pluralsight.com as well as on frontendmasters.com

Next JavaScript books in my Wishlist:

This is not where it stops, if you want to know more about which JavaScript books are next in my wishlist, then you can check them here on amazon: http://amzn.to/29GxIq3

Free JavaScript Ebooks:

If you don’t want to buy anything and only looking for online or free PDF resources, then you can get many free JavaScript ebooks here: http://jsbooks.revolunet.com/

 

Good friends don’t forget to share good resources with their friends, so share it with your friends as well.

Fix Uncaught ReflectionException: Class log does not exist …/laravel/framework/…

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

I again got this error which left me no clue of what happened wrong and how can I fix it.

PHP Fatal error: Uncaught ReflectionException: Class log does not exist in .../vendo/laravel/framework/src/Illuminate/Container/Container.php:741

I tried to find solution on google for a while and came to know that this don’t tell what acually went wrong. There can be different things which can be in different case. And you will find nothing other than someone will be telling that this error just mean something crashed earlier on before that interface was bound. So it tells nothing useful.

I found different reasons for this, but most commonly it was after you updated something in your system, which effected some extension of php or something else went wrong.

Here I am not going to dig deeper into why it happened because there can be lot of different reasons, I am just trying to tell a way by which I came to know the reason and fixed it. It happened to me twice in last few months and I found nothing on stackoverflow so that’s why I am writing it here.

So here are steps to find the reason and fix:

  1. Good thing about Laravel is that it checks some obvious dependencies which are required for Laravel to function properly. So go to some other directory and try installing Laravel’s same version there.  You can install it using
    composer create-project --prefer-dist laravel/laravel blog

    while in my case I was using Laravel bootstrap so I ran

    composer create-project graham-campbell/bootstrap-cms --prefer-dist -s dev
  2. It will show you missing dependencis, so you can see the dependencies and try to resolve them by installing missing extensions. In my case it was ext-mbstring  missing and in someone else’s case it was php-mysql extension missing. So install whatever extension is missing in your case.
  3. After installing extension don’t forget to restart apache:
    sudo service apache2 restart
  4. Once you have those extensions installed and your able to complete Laravel installation, go back to actual Laravel installation directory where you were actually facing above mentioned issue.
  5. Once you are there, give all permissions to `storage` and `bootstrap/cache` directories in Laravel installation by doing:
    sudo chmod 777 storage -R
    sudo chmod 777 bootstrap/cache -R
  6.  Now execute following command:
    php artisan clear-compiled
  7. If you see error like:
    PHP Fatal error: Trait 'Illuminate\Auth\Access\HandlesAuthorization' not found in ...dynamic/bootstrap/cache/compiled.php on line 737
    Script php artisan clear-compiled handling the post-install-cmd event returned with an error[RuntimeException]Error Output: PHP Fatal error: Trait 'Illuminate\Auth\Access\HandlesAuthorization' not found in /var/www/html.../bootstrap/cache/comp

    Delete the contents of the bootstrap/cache folder, then run

    php artisan app:update 

    and try running

     php artisan clear-compiled

    again.

  8. After doing so just run:
    composer dump-autoload
  9. And then go to your browser and try to reload. Most probably it should be working as this is how I had it working twice.

In case it still don’t work, then post it in comment and we can try to dig into that.

How to setup Atom for PHP Development

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

What is Atom and why it is awesome?

Atom is a hackable text editor. I normally don’t like the idea of text editors which need settings and different plug-ins installations to be some what equivalent to a complete IDE but after using Atom with some configurations and plug-in installation, my opinion is changed.

What now I think is that a hackable editor is actually good because it provide you option to only have functionality what you exactly need while still being very light-weight.

Using Atom as PHP IDE:

I came to Atom from Netbeans, when it became very slow and made overall system very slow. I never liked Netbeans’ non-smooth fonts on Ubuntu but didn’t find any good option. But after slowness issue, I tried Atom as text editor and then found it much more powerful by utilizing packages available. So now I use it for PHP development with useful features without making my system slow.

Please note that these packages will not make it equivalent to a premium tool like “PHP Storm”( in fact never compare other IDEs with JetBrains’ IDEs unless you don’t want to pay 100$+ for IDE. ), but still Atom with packages will be better experience in many ways as compared to other editors and IDEs. If you are currently using some text editor like notepad++ or brackets, or tools like Aptana or Eclipse, you will like Atom with these packages. And obviously your system will feel much better if you are coming from Netbeans.

Installing Atom:

Simply go to https://atom.io/ and download the build for your release and then simply install it. It don’t have any hard dependency like Netbeans need JRE. By just installing Atom, you can start using it as a simple text editor with smoother fonts and awesome themes.

Atom for JS:

Most of PHP developers also need to interact with JS and front-end. So you will want JS support as well. Atom come with some JS related packages already installed with Atom.

Atom Settings and packages:

To see atom packages, themes and other configurations then go to:

Top menu > Packages > Settings View > Open

or

simply press ctrl + , (control and comma key)

You should see this settings screen:

Now scroll down and find field labeled as Tab Length” and change its value to 4 instead of 2 as per PSR2 standard. ( http://www.php-fig.org/psr/psr-2/ )

Atom Packages:

In atom, you need to install packages to extend Atom and have more feature set. Here are some important packages listed below with their detail. Please note that Atom package can be installed using settings window as well as this command:

$ apm install <package-name>

PHP CS Fixer:

csfixeronsave

PHP CS fixer runs the “PHP Coding Standards Fixer” within your Atom Editor. Install this package but it will not start functioning. This package requires the “PHP Coding Standards Fixer” Cli build by SensioLabs wich can be installed using composer:

$ ./composer.phar global require fabpot/php-cs-fixer

Above package is abandoned so this one can be used:

$ ./composer.phar global require friendsofphp/php-cs-fixer

then go to settings provide path to php-cs-fixer and PHP. Also click on “Execute on Save” check box so that on save, it will format it according to psr2 standards.

Linter PHP:

linter-php error screen
linter-php error screen

Install this package so that your Atom know in case of any PHP syntax error  you make. It will show you proper error within your editor. This is very important unless you used to write PHP in conventional text editor.

It will work without any further settings if your php is accessible globally through command line. Otherwise you will need to provide PHP executable path in this package’s settings.

PHP Hyperclick:

Hyperclick provider for PHP. Open file when classname is clicked. This is simple and very useful package but installing it alone will not work. So you will also need to install dependency  that is Hyper Click (another package of Atom).

In case if it don’t work with “ctrl+click ” then try “alt+ctrl+click” .

Last words:

These are just few packages that I have installed and made my Atom editor  better, at least I no more miss Netbeans (which I was using for last ) for doing some work in modern framework like Laravel. But I expect a lot of more awesome surprising packages other than these. So keep exploring and let me know about your favorite atom packages in comment.

 

Installing MongoDB Driver (with MongoDB extension) on Ubuntu and other Linux distro.

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

Previously “Mongo” was the extension used for MongoDB (Legacy) driver for PHP. Now that is depreciated. Now “MongoDB” Pecl extension is used instead of  “Mongo” Pecl extension. And MongoDB Driver is PHP’s official driver for MongoDB. Here is detail of this driver on php.net: http://php.net/manual/en/set.mongodb.php . It supports PHP as well as HHVM.

To have this MongoDB driver working, you need to install pecl “MongoDB” extension.

To install PHP MongoDB on Linux, follow below mentioned steps:

  1. Run this command:
    sudo pecl install mongodb
  2. Then add following line to php.ini
    extension=mongodb.so
  3. Then you need to restart your apache or nginx . If you are using apache then use following command to reload it.
  1. service apache2 reload

    To test your installation try instantiating “MongoDB\Driver\Client” by using code similar to this one:

    $client = new MongoDB\Driver\Client("mongodb://localhost:27017");

    If it says that MongoDB\Driver\Client not found or not defined then there is chance that MongoDB driver is not properly installed. However parameters to this constructor can be changed depends on your MongoDB URL.

    In case of any problem, feel free to let me know in comments section.

Fundamentals of D3 visualisations

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

D3.js is a popular SVG based data visualization library and there are many reasons for its popularity. D3.js provides foundations and components for creating data visualizations instead of providing some already built charts. Another big reason of D3.js popularity is that it don’t use a new technology but rely on existing web standards.

  1. HTML
  2. CSS
  3. DOM
  4. SVG

Probably some of you have heard about SVG but don’t know what exactly it is. SVG stands for Scalable Vector Graphics. If you guys haven’t much time and want to know very basic of SVG then see http://www.w3schools.com/svg/ . If you are one of those guys who want to study in detail then this book named SVG Essentials seems promising.

There are 3 things at which D3.js is very good.

  1. Data manipulation and calculations
  2. DOM manipulation
  3. SVG creation and manipulation

In fact D3 magic depends on these 3 things together. D3 embeds Data in DOM after manipulation and parsing it in different ways and use SVG where graphics is required.

Data Manipulation and Calculations:

D3 stands for Data Driven Documents. So first D in D3 stands for Data.  And D3 provides different ways for manipulating data and doing different calculations. For example, D3 provide different array related methods as shown here: https://github.com/mbostock/d3/wiki/Arrays .

Other than arrays D3 also have variety of methods to work with time and time intervals, detail can be found here: https://github.com/mbostock/d3/wiki/Time-Intervals

DOM Manipulation:

It is easy to Manipulate and Bind data with DOM. A simple bar chart code can be seen here as well:

<html>
<head>
<style>
/* set the CSS */
body { font: 12px Arial;}
.bar {
display: inline-block;
width: 20px;
height: 75px;
background-color: teal;
border:solid 1px #fff;
}
</style>
</head>
<body>
<script>
function getDataValue(d) {
	var barHeight = d * 5;
	return barHeight + "px";
}

d3.select('body').selectAll('div').data(dataset).enter()
        .append('div').attr('class', 'bar').style('height', getDataValue);

</script>
</body>
</html>

Here we only utilized D3’s interaction capabilities with DOM instead of using any SVG related feature. While SVG is much more feature rich when it comes to visualizations.
 

SVG Creation and Manipulation :

D3 can utilize HTML DOM elements to visualization as well but actual format used for visualization by D3 is SVG. It is because SVG provide a lot more variety of graphical features than an HTML DOM. A very basic thing you can do in D3 is to draw and SVG line. But this is not the limit, you can create shapes, polygons and different gradients etc. In fact you can do whatever you can do in other vector graphics tool like Adobe Illustrator and Inkscape.  Also D3 can provide very good animation related functionality as well.

Data Visualization Steps using D3.js

There are 3 major steps.

  1. Have data parsed and formatted based on how you need it to draw its visuals.
  2. Bind an SVG element in DOM.
  3. Draw whatever you want in SVG element.

There can be more steps if you want behavior, animation and user interaction however above mentioned steps are major steps.

Recommended Book

Although there are many books on D3.js. But if you want to learn it in detail then this book: Interactive Data Visualizations for the Web by Scott Murray can be very helpful. However, I will talk more about D3 its learning resources in next posts so if you don’t have time for book, you can still know more learn D3.js. But keep in mind that blog is no replacement of such awesome book.

Should I use D3 for creating charts and graphs?

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

What is D3 ?

D3.js is an open source Javascript library intended for data visualization purpose. “D3” stands for Data Driven Documents. It can also be used for creating and manipulating SVG files.  And different charts or graphs can also be plotted using D3 easily.

How D3 is different?

D3 is not similar to other charting solutions like Fusion charts and high charts etc. It don’t just take JSON and render a graph based on some predefined options but D3 let you plot the whole graph. It is comparatively low level library where developer plot the graph and create all graph elements and define its behavior. Although that is more time consuming but that also provide complete control in developer’s hand so it is very flexible. You render each and every element how you want it.

In  case of other charting solutions you choose which type of chart you want to plot and some other configurable options and call the function which renders graph/chart. That type of graph rendered and that’s all. Then it all depends on charting solution that what it returns. Some returns canvas based result while some renders an SVG.

When to Use D3 ?

A common understanding is that D3 should be only used if you are going to draw a graph which nobody has ever built. This is wrong. This can be the one reason but it is not the only one. If you simply want to customize the charts and want to look and work it exactly like some design, then D3 is something you can use. At  the same time one need to understand that it is something that will consume more time.

Another reason can  be to use D3 when you want every day graphs but you want them to  be look much different and behave different than what other frameworks are providing. If you want some extra elements that no charting solution is providing then D3 can be an option. As D3 is something which let you actually plot graphs and manipulate SVG elements through basic building blocks so by using those building blocks, you can create your own graphs with lot of flexibility.

D3 is very much useful when at time of starting building graph, your requirements are open ended and your clients don’t want to compromise on what they want. Other libraries graphs can have limits because they are already plotted with fix number of options so they will be rendered accordinlgy, while in D3 every element is placed by developer as he want it.

Why not customize other Charting solutions?

Many managers or people concern about deadlines often ask this question. Obviously time-line is important. No solution is good solution if it can’t be provided on time. First of all customizations can be of two types: Appearance and behavior.

Appearance can be customized through CSS if SVG is rendered by charting library.  But in case of chart’s or graph’s behavior, options are limited. There are many options which can be passed in JSON at time of initialization but still a chart or graph can render what it have. If you simply don’t have some option like if you want crosshair values to appear separately and your charting library provide it along with crosshair line then you normally cant change that.

So in short it can’t provide that level of flexibility that D3 can. So in case you have tight deadline and open ended requirements then you need to choose smartly between those two things.

What about D3 based charing libraries?

There are charting libraries which are based on D3. One example is C3.js . C3 is based on D3 and have cleaner API as well but it still don’t provide as much flexibility as D3 can. However, if you find limitations in C3 solution you can start using D3 there as well. But problem is that once you are using C3 and getting SVG, then to customize via d3 you need to manipulate that SVG directly and direct SVG manipulation is very low level thing. So that can even consume more time because in D3 you don’t always need to draw every SVG element but to customize a rendered SVG you may need to manipulate every single item.

So for flexibility should you never use D3 based charting libraries?

Actually you can use them but if you want more flexibility then either use D3 directly or use that D3 based charting library which provide you access to D3 components directly.

For example if that library make D3 axis and scale function and generate graph based on that, then it is better if you can access those same scale and axis function to use with D3. So that you can render them or change them if you want instead of using D3 to just change SVG elements of rendered graph.

Are there good resources for learning D3?

Actually D3 has a detailed documentation which is I think enough to understand D3. Also there are many D3 examples available as well as some books are written on D3 which can provide understanding of D3 to start.  There are also some video trainings available but I think those are mainly on data visualizations rather than on D3.

Is D3 easy to learn?

Actually with D3 documentation, I think it is easy to learn but you need to have a good mathematical mind. At-least a mind which don’t mind doing some calculations because many times you will be telling it where to render what. After all, great power come with great responsibility.

 

Configuring and using Laravel with MongoDB

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

In this article we will see how to use MongoDB with Laravel (PHP framework). So first we need to install MongoDB and Laravel.

Laravel and MongoDB installation:

We will install Laravel and MongoDB one by one and I assume that you have PHP already installed with a web server.

Laravel Installation:

I assume LAMP environment is already configured. You can install Laravel simply through composer using following command if you have Composer already installed.

composer create-project laravel/laravel --prefer-dist

If you don’t know about composer or want to know more detailed installation and configuration of Larvel then Laravel documentation explained it in detail: http://laravel.com/docs/5.1#installation

MongoDB installation:

If you haven’t already installed MongoDB then MongoDB have separate guides for installing it own different Operating Systems. So check that: http://docs.mongodb.org/manual/installation/

Current version of MongoDB at this time is 3.x. But it you have MongoDB version 2.x installed and running on your machine then still feel free to use this tutorial, as it will work for 2.x as well and it have stuff related to 2.x difference in user creation section.

MongoDB driver for PHP:

PHP have official MongoDB driver that is called Mongo. It contains MongoClient class that is used by several packages which connect PHP with MongoDB.

You can install MongoDB driver on Windows OS using steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-windows

To install MongoDB driver on ubuntu  or other Linux distributions, follow steps mentioned here: http://haafiz.me/development/installing-mongodb-driver-mongoclient-for-php-on-ubuntu

To check if MongoDB driver is successfully installed, try instantiating MongoClient class.

Laravel Package for MongoDB:

Laravel have several MongoDB related packages and some of them not work for Laravel 5.x (current versions at time of this writing). Based on several factors like number of contributers, number of commits, releases and documentation on github, simplicity and ease of use, I suggest using jenssegers/laravel-mongodb which is also knowns as Moloquent.

Installation:

To install for Laravel 5.1, install latest stable version using composer.

composer require jenssegers/mongodb

In config/app.php :

Add below line in providers array:

Jenssegers\Mongodb\MongodbServiceProvider::class,

And add in same file, add below line in aliases array:

'Moloquent' => 'Jenssegers\Mongodb\Model',

Moloquent Configurations:

In app/config/database.php, add MongoDB connection detail:

'mongodb' => array(
            'driver' => 'mongodb',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', 27017),
            'database' => env('DB_DATABASE', 'l5'),
            'username' => env('DB_USERNAME', 'l5'),
            'password' => env('DB_PASSWORD', '123456'),
            'options' => array(
                'db' => 'admin' // sets the authentication database required by mongo 3
            )
        ),

and make this mongodb connection, default connection.

'default' => env('DB_CONNECTION', 'mongodb'),

If you have installed MongoDB just now then you will not have Database, username and password to provide in connection info. For that purpose you need to first create database, username and password.

Setting up MongoDB Database and User:

To create a MongoDB database, you need to start, execute “mongo” from command line. To do so you need to add MongoDB bin directory to your system path. And then run:

mongod

This will run mongo server to listen calls.

In case you see error like: “data/db not found” , then that means that this path doesn’t exist on your system or don’t have appropriate permissions. So either create and assign appropriate permissions at that location or with appropriate permissions create DB data folder at some other custom location and give DB path like:

mongod --dbpath custom/directory/path

Once it is running, mongo server will be listening for client calls. So you need to run mongo shell client by simply opening another shell instance and run :

mongo

This will open mongoDB shell.

Creating Database in MongoDB:

Using mongo client shell, you need to create your database

> use dbname
> db.insert({"key":"value"})

By executing above statement, use statement switches DB to “dbname”, and assigns value “dbname” to variable “db”  so you can use your desired DB name. If “dbname” is name of existing database then it will switch to that database or else it will create that Database if atleast one record is added to that database.

Setting up First User and access:

If you are using Mongo 3.0 or above, first of all you need to switch to “admin” database and creating a user with administrative rights for all databases.

> use admin
> db.createUser(
  {
    user: "siteUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

You can replace “siteUserAdmin” and “password” from above code with your desired admin username and password. Role “userAdminAnyDatabase” is a special role for administrating all databases and this role is at “admin” database.

Once you have this Admin user on admin DB, you need to create user for your required DB, in our case “dbname”.

> use records
> db.createUser(
  {
    user: "recordsUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdmin", db: "records" } ]
  }
)

Here you can replace “recordsUserAdmin”,”password” and “dbname” with desired username, password and your intended database name. And this will set your admin user for that database.

If you are using MongoDB version 2.x then user creation is different. In version 2.x db.createUser() function is not present. You need to use db.addUser() like:

> use products
> db.addUser( { user: "user1",
              pwd: "password",
              roles: [ "readWrite", "dbAdmin" ]
            } )

So now you have DBname, username and password to put in you Laravel app/config/database.php

Extending Models from Moloquent:

Only thing that is left is to extend your models from “Moloquent” instead of “Eloquent”.  So a typical model will look like this:

<?php
namespace App\Models;

use Moloquent;

/**
 * Category Model
 *
 * @author Hafiz Waheeduddin
 */
class Category extends Moloquent
{
 public function tasks()
 {
 return $this->hasMany('App\Models\Task', 'category_id');
 }
}

So after that you can simply run most of queries of query builder through category model. And can utilized ORM in similar way as Moloquent supports many types of relationships, so you can utilize them too.

Moloquent Detail and Documentation:

Moloquent have very good examples at github to understand it and use it. So for Moloquent usage, reference and understanding, please check moloquent github page .

Installing MongoDB driver for PHP on Ubuntu and other Linux distributions

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

Mongo is official MongoDB driver for PHP. Here is detail of this driver on php.net:  http://php.net/manual/en/mongo.manual.php . Mongo include MongoClient class which is required to connect MongoDB and required by several packages that bridge between MongoDB and PHP.

MongoClient works on almost all of Operating Systems including Windows, Mac OS X, Unix, and Linux; little- and big-endian machines. No matter 32 or 64-bit machines. PHP 5.3 through 5.6. To install it, there is a “mongo” package on PECL.

To install PHP Mongo on Linux, follow below mentioned steps:

  1. Run this command:
    sudo pecl install mongo
  2. If response of above command is error with text “phpize not found” then you need to first run this command and then above one. Please note that this command is useful on Debian based distributions, for others please use appopiate command accordingly :
    sudo apt-get install php5-dev
  3. Then add following line to php.ini
    extension=mongo.so
  4. Then you need to restart your apache or nginx . If you are using apache then use following command to reload it.
  5. service apache2 reload

    After this hopefully your PHPClient class will be working fine and you can test your code which use MongoClient class.

    In case of any problem, feel free to let me know in comments section.

Installing MongoDB driver for PHP on Windows

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • Digg

 

mongoPHP-logo

MongoClient class is included in “Mongo” that is official MongoDB driver for PHP. MongoClient class is required to connect MongoDB and required by several packages that bridge between MongoDB and PHP. Here is detail of this driver on php.net:  http://php.net/manual/en/mongo.manual.php

Mongo works on almost all of Operating Systems including Windows, Mac OS X, Unix, and Linux; little- and big-endian machines. No matter 32 or 64-bit machines. PHP 5.3 through 5.6. To install it, there is a “mongo” package on PECL.

To install Mongo for Windows, you need to do following steps (Tested with Windows 7) :

  1. Download this package from PECL website manually. Go to PECL Mongo package and choose latest stable version’s DLL by clicking on DLL link.
  2. Choose Thread safe x86 version, even for 64 bit system and download it. 64-bit version didn’t work for some people while x86 on 64-bit system worked fine so use download x86 thread safe version.
  3. Extract the zip file that is just downloaded, and place it in your PHP’s ext (extensions) directory. Ext directory can be find through phpinfo().
  4. Once placed in PHP’s ext directory, open your php.ini file and add follwing line and save it:
    extension=php_mongo.dll
  5. Then restart your apache server and test your code which use MongoClient class. It should work now.

In case of any problem, feel free to ask in comments.