প্রত্যেক বাবা মাই চায় তার সন্তান আদর্শ মানুষ হোক, কিন্তু অজান্তে ভুল করছেন না তো?

আফসানা শিউলি একজন কর্মজীবী মা। তার দুটি সন্তান। কর্মজীবী হলেও সন্তান-লালন এর ক্ষেত্রে আফসানা শিউলি খুবই সতর্ক। তিনি প্রায়ই সন্তানদের স্কুলে যান। স্কুলে তাদের বন্ধুদের সাথে ও বন্ধুদের বাবা-মায়ের সাথে গল্প করেন। অন্যান্য অভিভাবকদের সাথে প্রায় সময়ই তিনি তাদের সন্তান-লালন ‘এর বিষয়টি নিয়ে আলোচনা করেন। মূলত, মিস. আফসানা প্রত্যেকের কাছ থেকে সন্তান-লালন এর ভাল ভাল উপায় গুলো জানতে আগ্রহী। যাতে করে, নিজ সন্তানদের লালন-পালনে সবচেয়ে উত্তম পন্থাটি প্রয়োগ করতে পারেন।

কিন্তু আমাদের সমাজের প্রকৃত চিত্র এমন নয়। সত্য কথা বলতে গেলে অনেক সময় ঠিক বিপরীত। যদিও সব বাবা-মাই চায় নিজের সন্তান-লালন ‘এর সবচেয়ে উত্তম পন্থাটি প্রয়োগ করতে। কিন্তু বেশিরভাগ মনোবিজ্ঞানীদের মতে অনেক অভিজ্ঞ বাবা-মাও সন্তান-লালন ‘এ না বুঝেই মারাত্মক রকমের ভুল করে থাকেন।

তাহলে আসুন জেনে নেই, এরকম কিছু ভুল যেগুলো হয়ত আপনিও করছেন না বুঝেই!

১. চুরি করা তো খুবই খারাপ (কিন্তু? ) :

‘চুরি করবে না’ বা ‘কারও কিছু না বলে ধরবে না’ এই বাক্য দুটি বাবা-মা সবচেয়ে বেশি ব্যবহার করেন। এটি অবশ্যই ভাল একটি উপদেশ। কিন্তু সন্তান লালন এর ক্ষেত্রে হতে হবে আরেকটু কৌশলী এবং নরম।

মনোবিজ্ঞানীগন এখানে শিশুদের অন্য একটি বিষয় নিয়ে কথা বলছেন। তারা মনে করেন, শিশুরা বাবা-মা বা শিক্ষকদের বকা খাওয়ার ভয়ে কোন অন্যায় করলে বলতে চায় না। এই যে তাদের মাঝে বকুনির ভয়ে অন্যায় লুকিয়ে ফেলার যে একটা মানসিকতা তৈরি হয়েছে, এটি ভাল লক্ষণ নয়। তাই, আপনার সন্তান-লালন ‘এ সন্তান যা বলতে চাচ্ছে তা প্রথমে শুনুন এবং তা যেরকমই হোক, কোন রকম বকা-ঝকা না করে খুব সুন্দর করে বিষয়টি সমাধানের চেষ্টা করুন।

২. ‘বাচ্চাদের খারাপ লাগতে পারবে না’ এরকম ভাবাটা ভুল:

অনেক সময় বাবা-মা তাদের সন্তানদের কোন কিছুর জন্য কান্নাকাটি বা রেগে যাওয়া দেখলে বিরক্ত হন। অর্থাৎ, সন্তানের রেগে যাওয়া বা কান্না করা যাবে না’- বাবা-মায়ের এরকম মনে হওয়াটা খুবই ভুল একটি বিষয়। যেমন অনেক সময় বাচ্চারা রেগে গেলে খেলনা ছুড়ে ফেলে বা কোন কিছু না পেলে চিৎকার শুরু করে। এরকম সময়ে আমরা প্রায়ই সন্তানদের ধমক দিয়ে থাকি। আর মনে করি যে এই ধমক দেয়াটা তো খুবই স্বাভাবিক একটা বিষয়।

কিন্তু মনোবিজ্ঞানী রা বলছেন ভিন্ন কথা। তাদের মতে, সন্তান লালন এর ক্ষেত্রে বাবা-মায়ের এহেন আচরণ বিপদজনক বিপদজনক।এখানে সন্তানদের ধমক দেয়ার বদলে কেন তারা কাঁদছে এর কারণ বের করার চেষ্টা করা উচিত।

৩. আমার বাচ্চাকে সবাই ভাল বললেই সে ‘ভাল’ :

‘আমার ছেলে কে এ পাড়ার সবাই পছন্দ করে’ -এটি প্রায় সব বাবা-মাই মনে করেন। কিন্তু, যদি বলা হয় যে এটা আদর্শ সন্তান লালন এর অন্তরায়, তাহলে অবাক হবেন না কিন্তু! কারণ, এটাই প্রকৃত সত্য।

বাবা মায়েরা প্রায়ই সন্তানদের সবার সাথে মিলেমিশে চলার কথা বলে থাকেন, যা খুবই ভাল উপদেশ। কিন্তু এই উপদেশ পালন করতে গিয়ে তারা অনেক অন্যায়কেও নীরবে মেনে নেয়। এবং এটিই সন্তানের মানসিক বিকাসের বাধা বলে মনোবিজ্ঞানীরা মনে করছেন মনোবিজ্ঞানীরা মনে করেন।

৪. পরীক্ষায় ভাল না করলে জীবনে কোন উন্নতি করতে পারবে না :

এই কথাটির সাথে আমরা মোটামুটি সবাই পরিচিত। অর্থাৎ বর্তমান বাবা মায়েরাও যখন ছোট ছিলেন, তখন তারাও নিশ্চয় এই উপদেশ শুনেছিলেন! এ কথা সত্য যে, বর্তমান সময় অনেক প্রতিযোগিতার সময়। তাই বলে পরীক্ষার রেজাল্ট দিয়ে সে প্রতিযোগিতায় জয়ী হওয়া যায় না। জয়ী হতে হয় মেধা ও বুদ্ধি দিয়ে।

কিন্তু দুঃখের বিষয় হচ্ছে, বাবা-মায়েরা সন্তান-লালন ‘এর ক্ষেত্রে প্রায়ই সন্তানের স্কুলের রেজাল্ট এর জের টেনে নিয়ে আসেন, সন্তানের যোগ্যতা প্রমানের জন্য। এর দ্বারা আপনি একে ত মস্ত ভুলই করছেন, আবার উলটো সন্তানের যতোটুকু প্রতিভা আছে, সেটুকুও নষ্ট করে দিচ্ছেন।

এটা আমার কথা নয়, মনোবিজ্ঞানীদের কথা। বিশ্বাস না হলে এই লিংকে গিয়েই দেখুন!

৫. বাচ্চাদের মানসিক বিকাশের জন্য দামি দামি খেলনা ও যন্ত্রপাতির প্রয়োজন :

সম্প্রতি আমেরিকার মনোবিজ্ঞানীগন গবেষণা করে বের করেছেন যে, ‘প্রতি বছর বাবা-মা সন্তানদের মানসিক বিকাশের জন্য প্রচুর অর্থ ব্যয় কতে খেলনা কিনে থাকেন।’ দামী খেলনা ক্রয়ের এই ব্যয়ে হার দিন দিন বাড়ছে ফলে অনেকেই খরচের ভয়ে সন্তান নেয়াতে নিরুৎসাহিত হচ্ছে।

মনোবিজ্ঞানীদের মতে এটিও সন্তান-লালন ‘এর ক্ষেত্রে বাবা-মায়ের একটি বড় ভুল ধারনা। কারণ, প্রায় সব বিজ্ঞানী বা মনীষিগন দামি খেলনা, এমনকি কোন খেলনা ছাড়াই বড় হয়েছে। সুতরাং, দামী খেলনা বা যন্ত্রপাতির সাথে সন্তানের মানসিক বিকাশের কোন সম্পর্ক নেই।

৬. পড়ালেখার পাশাপাশি কিছু না কিছু করতেই হবে :

মালিহা জামান একজন গৃহিনী। তিনি তার একমাত্র মেয়ের পড়ালেখাসহ সার্বিক উন্নয়নের প্রতি খুবই মনযোগী। তার মেয়ে মাইশা, স্কুল শেষ করে সপ্তাহে ৩ দিন শিশু একাডেমিতে গান শেখে। আর তিন দিন শেখে আর্ট। এছাড়া সপ্তাহে বাকি ১ দিন স্কুলের অভিনয় গ্রুপের সাথেও সে অভিনয় চর্চা করে মাইশা। মা হিসেবে মালিহা জামান এ নিয়ে খুবই গর্ব বোধ করেন যে তার সন্তান অন্যদের চেয়ে দ্রুত জ্ঞানী হয়ে যাচ্ছে।

কিন্তু মনোবিজ্ঞানীরা বলছেন এর সম্পূর্ণ বিপরীত কথা। তাদের বক্তব্য হচ্ছে বাচ্চারা কখনই জোর করে ঘারে কিছু চাপিয়ে দিলে শিখতে পারে না যতক্ষণ না তাদের নিজেদের মত করে ছেড়ে দেয়া হচ্ছে। তাই সঠিকভাবে সন্তান-লালন ‘এর জন্য তাদের প্রতিদিন কিছু সময় নিজের মত করে ছেড়ে দিন।

প্রত্যেক বাবা মাই চায় তার সন্তান আদর্শ মানুষ হোক। পড়ালেখা, খেলাধুলা ইত্যাদি সমস্ত ক্ষেত্রেই তারা সবার থেকে এগিয়ে থাকুক। তাই, তাদের মানসিক বিকাশের জন্য, পরীক্ষায় ভাল ফলাফলের জন্য বাবা-মায়ের থাকে নিরন্তর প্রচেষ্টা। কিন্তু সন্তান-লালন ‘এর ক্ষেত্রে আমরা অনেকেই নিজের অজান্তেই এমন অনেক ভুল করে চলেছি যেগুলো সন্তানদের উন্নতির জন্য হচ্ছে বাধা।

কৃতজ্ঞতাঃ অন্যরকম বিজ্ঞানবাক্স

Advertisements

Laravel Interview Questions And Answers

1. What is Laravel

Laravel is free open source “PHP framework” based on MVC Design Pattern.
It is created by Taylor Otwell. Laravel provides expressive and elegant syntax that helps in creating a wonderful web application easily and quickly.

2. List some official packages provided by Laravel

Below are some official packages provided by Laravel

  • Cashier :Laravel Cashier provides an expressive, fluent interface to Stripe’s and Braintree’s subscription billing services. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Cashier can handle coupons, swapping subscription, subscription “quantities”, cancellation grace periods, and even generate invoice PDFs.
  • Envoy :Laravel Envoy provides a clean, minimal syntax for defining common tasks you run on your remote servers. Using Blade style syntax, you can easily setup tasks for deployment, Artisan commands, and more. Currently, Envoy only supports the Mac and Linux operating systems.
  • Passport :Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the League OAuth2 server that is maintained by Alex Bilbie.
  • Scout :Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.
  • Socialite :Laravel Socialite provides an expressive, fluent interface to OAuth authentication with Facebook, Twitter, Google, LinkedIn, GitHub and Bitbucket. It handles almost all of the boilerplate social authentication code you are dreading writing.

     

3. What is Lumen?

Lumen is PHP micro framework that built on Laravel’s top components. It is created by Taylor Otwell.
It is the perfect option for building Laravel based micro-services and fast REST API’s.
It’s one of the fastest micro-frameworks available.

4. List out some benefits of Laravel over other Php frameworks ?

Top benifits of laravel framework

  1. Setup and customization process is  easy and fast as compared to others.
  2. Inbuilt Authentication System.
  3. Supports multiple file systems
  4. Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel Scout.
  5. Eloquent ORM (Object Relation Mapping) with PHP active record implementation.
  6. Built in command line tool “Artisan” for creating a code skeleton ,database structure and build their migration.

5. List out some latest features of Laravel Framework

 

  • Inbuilt CRSF (cross-site request forgery ) Protection.
    Laravel provided an easy way to protect your website from cross-site request forgery (CSRF) attacks.
    Cross-site request forgeries are malicious attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated.
  • Inbuilt paginations Laravel provides an easy approach to implement paginations in your application.Laravel’s paginator is integrated with the query builder and Eloquent ORM and provides convenient, easy-to-use pagination of database.
  • Reverse Routing
    In Laravel reverse routing is generating URL’s based on route declarations.Reverse routing makes your application so much more flexible.
  • Query builder:
    Laravel’s database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.

    The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

  • Route caching
  • Database Migration
  • IOC (Inverse of Control) Container Or service container.

 

6. What is composer ?

 Composer is PHP dependency manager used for installing dependencies of PHP applications.
It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.

It provides us a nice way to reuse any kind of code. Rather than all of us reinventing the wheel over and over, we can instead download popular packages.

 

7. How to install Laravel via composer ?

   To install Laravel with composer run below command on your terminal.

composer create-project Laravel/Laravel your-project-name version

8. What is php artisan. List out some artisan commands ? 

PHP artisan is the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. Here are the list of some artisian command.

  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan –versian
  • php artisan make model model_name
  • php artisan make controller controller_name

9. How to check current installed version of Laravel ? 

 Use php artisan –version command to check current installed version of Laravel Framework

Usage:

php artisan --version

10. List some Aggregates methods provided by query builder in Laravel ?

Aggregate function is a function where the values of multiple rows are grouped together as input on certain criteria to form a single value of more significant meaning or measurements such as a set, a bag or a list

Below is list of some Aggregates methods provided by Laravel query builder.

  • count()

    Usage:$products = DB::table(‘products’)->count();

  • max()

    Usage:$price = DB::table(‘orders’)->max(‘price’);

  • min()

    Usage:$price = DB::table(‘orders’)->min(‘price’);

  • avg()

    Usage:$price = DB::table(‘orders’)->avg(‘price’);

  • sum()

    Usage: $price = DB::table(‘orders’)->sum(‘price’);

 

11. Explain Events in Laravel ?

An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation, that allow us to subscribe and listen for events in our application.An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation, that allows us to subscribe and listen for events in our application.

Below are some events examples in Laravel:-

  • A new user has registered
  • A new comment is posted
  • User login/logout
  • New product is added.

12. How to turn off CRSF protection for a route in Laravel ?      

 
To turn off or diasble CRSF protection for specific routes in Laravel open “app/Http/Middleware/VerifyCsrfToken.php” file and add following code in it

//add this in your class
private $exceptUrls = ['controller/route1', 'controller/route2'];

//modify this function

public function handle($request, Closure $next)
{

 //add this condition
foreach($this->exceptUrls as $route) {

 if ($request->is($route)) {

  return $next($request);

 }

}
return parent::handle($request, $next);}

13. What happens when you type “php artisan” in the command line?

  

When you type “PHP artisan” it lists of a few dozen different command options.

14. Which template engine Laravel use ?

 Laravel uses Blade Templating Engine.

Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.

 

15. How can you change your default database type ?       

By default Laravel is configured to use MySQL.In order to change your default database edit your config/database.php and search for ‘default’ => ‘mysql’ and change it to whatever you want (like ‘default’ => ‘sqlite’).

 

16. Explain Migrations in Laravel ? How can you generate migration . 

Laravel Migrations are like version control for your database, allowing a team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema.

Steps to Generate Migrations in Laravel

  • To create a migration, use the make:migration Artisan command
  • When you create a migration file, Laravel stores it in /database/migrations directory.
  • Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.
  • Open the command prompt or terminal depending on your operating system.

17. What are service providers in laravel ?

  Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel’s core services are bootstrapped via service providers.

Service provider basically registers event listeners, middleware, routes to Laravel’s service container.
All service providers need to be registered in providers array of app/config.php file.

 

 

PHP Laravel Interview Questions and Answers

We are going to share with you the top 10 interview questions and answers in PHP Laravel for your preparation purpose:

1- What is Laravel Framework?

Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern.

2- What are the main differences between Laravel 4 and Laravel 5.x?

Summarizing Laravel 5.0 Release notes from the above article: 1. The old app/models directory has been entirely removed.
2. Controllers, middleware, and requests (a new type of class in Laravel 5.0) are now grouped under the app/Http directory.
3. A new app/Providers directory replaces the app/start files from previous versions of Laravel 4.x.
4. Application language files and views have been moved to the resources directory.
5. All major Laravel components implement interfaces which are located in the illuminate/contracts repository.
6. New route:cache Artisan command to drastically speed up the registration of your routes.
7. Laravel 5 now supports HTTP middleware, and the included authentication and CSRF “filters” have been converted to middleware.
8. you may now type-hint dependencies on controller methods.
9. User registration, authentication, and password reset controllers are now included out of the box, as well as simple corresponding views, which are located at resources/views/auth.
10. You may now define events as objects instead of simply using strings.
11. In addition to the queue job format supported in Laravel 4, Laravel 5 allows you to represent your queued jobs as simple command objects. These commands live in the app/Commands directory.
12. A database queue driver is now included in Laravel, providing a simple, local queue driver that requires no extra package installation beyond your database software.
13. Laravel command scheduler allows you to fluently and expressively define your command schedule within Laravel itself, and only a single Cron entry is needed on your server.
14. The php artisan tinker command now utilizes Psysh by Justin Hileman, a more robust REPL for PHP.
15. Laravel 5 now utilizes DotEnv by Vance Lucas.
16. Laravel Elixir, by Jeffrey Way, provides a fluent, expressive interface to compiling and concatenating your assets.
17. Laravel Socialite is an optional, Laravel 5.0+ compatible package that provides totally painless authentication with OAuth providers.
18. Laravel now includes the powerful Flysystem filesystem abstraction library, providing pain free integration with local, Amazon S3, and Rackspace cloud storage – all with one, unified and elegant API!
19. Laravel 5.0 introduces form requests, which extend the Illuminate\Foundation\Http\FormRequest class. These request objects can be combined with controller method injection to provide a boiler-plate free method of validating user input.
20. The Laravel 5 base controller now includes a ValidatesRequests trait. This trait provides a simple validate method to validate incoming requests.
21. new Artisan generator commands have been added to the framework.
22. The popular dd helper function, which dumps variable debug information, has been upgraded to use the amazing Symfony VarDumper.

3- What is routing and how, and what are the different ways to write it?

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group. For most applications, you will begin by defining routes in your routes/web.php file.

4- What is Composer?

Composer is a dependency manager for PHP. Composer will manage the dependencies you require on a project by project basis. This means that Composer will pull in all the required libraries, dependencies and manage them all in one place

5- What is Laravel Eloquent?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

6- What is Luman?

Lumen is a new project from Laravel creator Taylor Otwell. It’s a “micro-framework”, meaning it’s a smaller, faster, leaner version of a full web application framework. It competes other popular micro-frameworks, Slim and Silex.

7- How to implement you own package in Laravel?

You can create a package in laravel using the following steps:
1. Package folder and name
2. Composer.json file for the package
3. Loading package via main composer.json and PSR-4
4. Creating a Service Provider
5. Create a Controller for your package
6. Create our Routes.php file
For more about how to build your own package in laravel visit: how to create a laravel 5 package in 10 easy steps

8- What is database migration? And how to use it to add insert initial data to database?

Migrations are like version control for your database, allowing your team to easily modify and share the application’s database schema. Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you’ve faced the problem that database migrations solve.
Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

9- What directories that need to be writable laravel installation?

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.

10- What is HTTP middleware?

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.
There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app/Http/Middleware directory.

A simple guide to Stripe Webhooks

How they work and a quick PHP tutorial

What are webhooks?

Webhooks are ‘user-defined HTTP callbacks’. When an event occurs, the originating site will send an HTTP post request to a (usually) third-party who can then do something with it.

As an example, if you pay for something with Stripe then it will send a webhook. This will contain lots of data that looks like this:

Stripe\Charge JSON: {
  "id": "ch_15qP2a2eZvKYlo2C4fpk2mXl",
  "object": "charge",
  "created": 1428760376,
  "livemode": false,
  "paid": true,
  "status": "succeeded",
  "amount": 4995,
  "currency": "usd",
  "refunded": false,
....and so on

You can check out a more complete version on Stripe’s API docs here.

Why should I care?

If you don’t work in technical services or you found this page whilst googling for fishing tips, you probably won’t.

On the other hand, it’s very useful for storing information about what’s happening with your Stripe account. As the co-founder of Hooked.io I built a company which trivialises getting notifications about payments, disputes and transfers.

It’s also good for things like collecting usage data and whatnot.

How can I get a webhook?

Easy! First get hold of the Stripe PHP Library and put it in your directory.

First set your Stripe secret key (available in the dashboard)

\Stripe\Stripe::setApiKey(“sk_test_dwndaindiawd232dad”)

Then we want to get the POST data that Stripe sends:

$input = @file_get_contents(“php://input”);

Then decode the json:

$event_json = json_decode($input);

This will produce the array that you saw above. Take a look with:

print_r($input);

From there you can do anything you like with the array data! Referencing individual values is very simple:

if $event_json->type == ‘charge.succeeded’ {
echo ‘You made some money! Hooray!’;
}

Obviously a basic understand of arrays will make life easier for you here.

This is a very simple example of course, and there are some security factors which you should consider such as never processing the same event twice.

It’s fairly simple to do this, simply store the event id in a database and check against it before processing your webhook.

That’s it! Hopefully you found this helpful.

Courtesy: MEDIUM

Save Codeigniter config data in MySql database

In this tutorial, I want to show you how to save the codeigniter config data in mysql database. It means we will save config data in mysql and can grab these data when we need to use in our project and can also edit form our site dynamically.

Step 1: Configuration

For application/config/routes.php file

$route['default_controller'] = "home";

For application/config/config.php file

$config['base_url'] = 'http://localhost/ci_config/';

and

$config['enable_hooks'] = TRUE;

For application/config/autoload.php file

$autoload['libraries'] = array('database');

and

$autoload['helper'] = array('url','form');

and

$autoload['model'] = array('Siteconfig');

For application/config/database.php file

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'ciconfig';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';

For application/config/hooks.php file

You need to add below code to your hooks.php file.

$hook['post_controller_constructor'] = array(
         'class'    => '',
         'function' => 'load_config',
         'filename' => 'my_config.php',
         'filepath' => 'hooks'
         );

You can learn more about hooks in the CI documentation here.

Setp 2: Creating Hooks file

Open new document in your favourite editor and type below code and save as application/hooks/my_config.php

   //Loads configuration from database into global CI config   function load_config()   {    $CI =& get_instance();    foreach($CI->Siteconfig->get_all()->result() as $site_config)
   {
    $CI->config->set_item($site_config->key,$site_config->value);
   }
  }

We grab the config data from our database by using Siteconfig model. And set the data to global CI config. So we need to create Siteconfig model in our model folder.

Step 3:Creating database

Create a database from your MySql admin as ciconfig and run below code in your mysql tool.

CREATE TABLE IF NOT EXISTS `config_data` (
  `key` varchar(255) NOT NULL,
  `value` varchar(255) NOT NULL,
  PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `config_data`
--

INSERT INTO `config_data` (`key`, `value`) VALUES
('sitedescription', 'Tutorials for Web development and design'),
('sitename', 'TutsforWeb');

Step 4:Creating Siteconfig model

Open new document in your favourite editor and type below code and save as application/models/siteconfig.php

class Siteconfig extends CI_Model {  public function __construct()  {   parent::__construct();  }  public function get_all()  {   return $this->db->get('config_data');
 }
 public function update_config($data)
 {
  $success = true;
  foreach($data as $key=>$value)
  {
   if(!$this->save($key,$value))
   {
    $success=false;
    break;  
   }
  }
  return $success;
 }
 public function save($key,$value)
 {
  $config_data=array(
    'key'=>$key,
    'value'=>$value
    );
  $this->db->where('key', $key);
  return $this->db->update('config_data',$config_data); 
 }
}

get_all() function is used in our my_config hooks file to grab all data from our database.

update_config() function is used to update our config data when the form is submitted from config view file.
save() function is called form the update_config() function to update one by one.

Step 5:Creating home Controller

Open new document in your favourite editor and type below code and save as application/controllers/home.php


if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Home extends CI_Controller {   public function index()   {    $this->load->view('home');
  }
  public function config()
  {
   $this->load->view('config');
  }
  public function update()
  {
   $update_data=array(
      'sitename'=>$this->input->post('sitename'),
      'sitedescription'=>$this->input->post('sitedescription')
      );
   $success = $this->Siteconfig->update_config($update_data);
   if($success) redirect("/home/index");
  }
}

Step 6:Creating view files

Open new document in your favourite editor and type below code and save as application/views/home.php

  


  
   config->item('sitename'); ?>
  

  

config->item('sitename'); ?>

config->item('sitedescription'); ?>

<a href="index.php/home/config">Site Config

As you see above code, we can use our config data by using this script

echo $this->config->item('sitename');

We need to create the config view file to edit config data dynamically. Open new document in your favourite editor and type below code and save as application/views/config.php

  
    echo $this->config->item('sitename');

echo form_open(“home/update”);
Site Name :
<input id="sitename" name="sitename" size="40" type="text" value="config->item(‘sitename’); ?>” />

Site Description :
<input id="sitedescription" name="sitedescription" size="40" type="text" value="config->item(‘sitedescription’); ?>” />


If you click the Site Config from our home page, this page will be loaded and you can edit and update our config data.

Happy Coding…..

5 New Features In PHP 7 That You Should Have A Look At

PHP is by far, the most preferred programming language. But is PHP 7 the most exciting releases of them all? Yes. The whole PHP community and the people linked to PHP, are all excited to welcome the biggest release for PHP in decades. It surely adds more versatility to the already versatile language.

But you must be wondering why PHP named its latest release PHP 7 and not PHP 6. Reason behind it is that, many of the PHP 6 releases were already implemented in PHP 5.3 and later, there was not really a proper reason just to change the name. What I am trying to say here is that we haven’t missed anything. Just to avoid the confusion with a dead project, PHP’s latest release was named to PHP 7.

Is This Hype Valid for PHP 7? What It Actually Brings Forth for the Developers?Hop on and let’s take a deeper dive. Let’s check out what new features PHP 7 has to offer. And what improvements those features will bring forth.

 

1. Speed Improvement

The developers for the PHP 7 has done a pretty commendable job here. Now your PHP codebase uses less memory and gives you even more performance than before. After it’s release, internet was overloaded with benchmarks which were really promising. It is almost a 2x increase inserver response times with PHP 7. For further details on benchmarks click here.

2. Implementation of Type Declarations

The type declaration is used to specify the type of variable. PHP sets this automatically and because of which, PHP is a weakly typed language. PHP does not need you to declare the data type. Because of which, you could do radical things with the variables, like adding Float into String without resulting in an error. Type declaration helps you get the expected results. Making sure that only certain procedures can occur. Which makes the code understandable.

In the previous PHP versions, we could use type hinting method. This method specifies the type of an argument declaration in a function. But the issue with this method was that you can only use it with a function declaration. Which limits to only two types, a class name, and an array.

Scalar Type Declaration

PHP 7 has now added Scalar type declaration for int, float, string, and boolean. Adding scalar type declaration and enabling strict requirements ensures that more correct and well-documented PHP programs can be written. It also helps you in gaining more control over your code and make the code easier to read.

By default, on PHP 7, these declarations are non-strict. Which means that the type forging is possible. As if you pass a string starting with a number into a float type function, it grabs the number from in the start and skips everything else. Passing a float into a function that requires an int, that float will become int.

Non-Strict Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getSum(float $a, float $b) {
   return $a + $b;
}
getSum(6, "7 week");
//Here int(6) changed to float(6.0) and string “7 week” changed to float(7.0)
//with a “Notice: A non well formed numeric value encountered”
//returns float(13)
getSum(1.1, "2.2");
//Here string "2.2" is changed to float(2.2) without any notice
//returns float(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)

Here the getSum function receives 2 floats and adds them together returning the sum. When you use a non-strict type declaration in PHP 7. It will reforge these arguments to match the type specified in the function. Which means whatever the argument we pass, PHP will convert it to float.

Strict Example

PHP 7 additionally gives us the opportunity to strict the declaration type. It is achieved by adding “strict_types=1” on the very first line of the file. This ensures that any calls made to the functions specified must strictly adhere to the specified types. Strict is determined in the file in which the call to a function is made and not the file in which the function is defined.

While using a strict type-declaration, if a mismatch occurs, a “Fatal Error” occurs and we know that something is not functioning as desired. This helps in not causing random and confusing diagnose issues. Let’s just cut the talk and take a look at an example with strict types turned on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
declare(strict_types=1);
function getSum(float $a, float $b) {
    return $a + $b;
}
getSum(3, "2 week");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given
getSum(1.8,  "4.5");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given
getSum(3.1, 2);
// int(2) change to float(2.0)
//returns float(5.1)

Setting “declare strict_type” to “1”, the first two calls that pass a string produces a Fatal error: “Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given”. With only the exception in the third call, in which if you pass an integer for an argument instead of a float value, PHP will perform “widening”, which includes adding .0 at the end of the integer value. This returns (5.1).

Return Type Declarations

The third type of declaration that PHP 7 supports are a Return Type Declaration. It supports all similar type arguments as a return. Take look at the example of how to specify a return type declaration.

1
2
3
function getSum(float $a, float $b) : float {
}

Adding a return type ensures that only an expected value type returns. For the previous two examples if we set the return type float it will work the same. As the values being returned are already float. So we will be doing an example for int. return types.

Non-Strict Integer Example

Without the strict type declaration on, if we specify the return type as int for the previous examples, it will work the same. With just the difference being, that return will be forged to an integer. Which means it will truncate the float value and only returns the integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function getSum(float $a, float $b) : int {
    return $a + $b;
}
getSum(6, "7 week");
// changes int(6) to float(6.0) & string(“7 week”) to float(7.0)
// returns int(13);
getSum(1.1, "2.2");
// changes string "2.2" to float(2.2)
// returns int(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)

Strict Integer Example

If we turn strict types on, we’ll get a Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned. For this case we’ll be casting our return value as an int. which then returns the truncated value.

1
2
3
4
5
6
7
8
9
declare(strict_types=1);
function getSum(float $a, float $b) : int {
    // return $a + $b;
    // The above statement shows Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned
    return (int)($a + $b); // truncate float like non-strict
}
getSum(3.1, 2); // changes int(2) to float(2.0) and returns int(5.1)

Benefits

These new implementations of Type Declaration certainly help in making the code easier to read. With PHP 7 you get a versatile type declaration methods which makes your life easier. You can even see at the start of the function, what is required and what will be returned.

3. Implementation of Error Handling

The next new feature we will be discussing are the new Error Handling techniques implemented in PHP 7. Handling fatal errors was a nightmare in previous versions of PHP. If a fatal error occurs it just simply stops the script rather than invoking the error handler. On a production server, this returns a blank white screen to your users, which in the end causes your credibility to drop.

But PHP 7 allows an exception to be thrown when an error occurs, rather than stopping the whole script. This doesn’t mean that Fatal errors are gone from PHP 7. They still exist i.e., an uncaught exception will still be a fatal error in PHP 7. One more thing to highlight here is that other types of errors like warnings and notices are unchanged in PHP 7. And exceptions are only thrown by fatal and recoverable errors only.

However, Error and Exception both in PHP 7 implements the new throwable class. This means both work almost the same way. Let’s see the new hierarchy to understand more.

-> Exception implements Throwable
    -> …
-> Error implements Throwable
    -> TypeError
    -> ParseError
    -> ArithmeticError
        -> DivisionByZeroError
    -> AssertionError

Under Error, PHP 7 now have some more specific errors. Which includes ParseError, TypeError, ArithmeticErrors and an AssertionError. Practically all errors that were fatal in PHP 5, now throw instances of Error in PHP 7, which in term help you to improve your code legibility.

4. New Operators

PHP 7 also brings us some new operators. Let’s just cut the talk and directly go through all the new operators.

Spaceship Operator

The first one in our list is the Spaceship Operator, also known as the Combined Comparison Operator. It is put together using three of the previous operators, namely, “<”, “=” and “>”. It looks something like this:

1
<=>

What this operator is useful for is that it will compare the value on the left to the value on the right and returns 3 different values. See the example below for further understanding.

1
2
3
4
5
6
7
$compareResult = $a <=> $b
if $a < $b it returns “-1” to the variable “compareResult”
if $a = $b it returns “0” to the variable “compareResult”
if $a > $b it returns “1” to the variable “compareResult”

A very useful operator. The most common use of this operator will be in sorting.

Null Coalesce Operator

Another new operator in PHP 7 is the Null Coalesce Operator. If it is not null it returns the left operand, otherwise, it returns the right operand. The thing worth mentioning here is that it won’t pop any notice if the left operand is a null variable.

1
$user = $userName ??  "v3ron";

In the above example, if the variable userName is not null, it will push that value to the variable “user”, or else “v3ron” will be assigned to the variable “user”.

Before PHP 7, something like this would be written as:

1
$user = isset($userName) ? $userName : “v3ron”;

And yes, these can be stacked which makes it much likely to be used. It will check each item from left to right until it finds one that is not null, it will use that value. For example:

5. CSPRNG Functions

The CSPRNG abbreviated as “Cryptographically Secure Pseudo-Random Number Generator” is an easy to use API. It provides an easy and reliable way to generate secure random integers and bytes for use within cryptographic contexts. It can be used especially for generating random passwords or password salt.

2 new functions have been introduced in PHP 7 to use namely, “random_int” and “random_bytes”. Let’s analyze a bit more to see what these two brings to the table for the developers.

Random Bytes

With random_bytes, you only supply a single argument that is the length of the random string which it will return in bytes. Take a look at the example for a better understanding.

1
2
3
4
5
$randomByte = random_bytes(10); // 10 is the length in bytes
var_dump(bin2hex($randomByte));
// output for the above code is: string(20) "5f655db3ae43c256937b"

These are bytes, not integers. For a random number or integer, you should use the random_int function.

Random Integers

This function generates secure random integers. When using random_int you supply two arguments, that are min and max. Which tells the minimum and maximum numbers for the random integer.

For example:

1
random_int(2,10);

The above code returns a random number between 2 and 10, including those two as well.

6. Conclusion

So much for all the new features. There are some features that have been removed in PHP 7, you can check them out by going to the deprecated features section in PHP 7.

Versions released before 5.5 are not compatible any longer. Now it is for you to decide whether to upgrade to PHP 7 for super fast speeds and update all your code accordingly. Or stay with the previous version of PHP.

PHP Libararies for working with MS Office

1. Microsoft Word

PHPWord – A library for working with Microsoft Word documents.
PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft Office Open XML (OOXML or OpenXML), OASIS Open Document Format for Office Applications (OpenDocument or ODF), Rich Text Format (RTF), HTML, and PDF.

2. Microsoft PowerPoint

PHPPowerPoint – A pure PHP library for writing presentations files.
PHPPowerPoint is a library written in pure PHP that provides a set of classes to write to different presentation file formats, i.e. Microsoft Office Open XML (OOXML or OpenXML) or OASIS Open Document Format for Office Applications (OpenDocument or ODF).

3. Microsoft Excel

PHPExcel – A pure PHP library for reading and writing spreadsheet files.
PHPExcel is a library written in pure PHP and providing a set of classes that allow you to write to and read from different spreadsheet file formats, like Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML, … This project is built around Microsoft’s OpenXML standard and PHP.

ExcelAnt – Simple yet powerful Excel manipulation library for PHP 5.4+.
ExcelAnt is an Excel manipulation library for PHP 5.4. It currently works on top of PHPExcel.

4. Extra

Csv – A CSV data manipulation library.
Csv is a simple library to ease CSV parsing, writing and filtering in PHP. The goal of the library is to be powerful while remaining lightweight, by utilizing PHP native classes whenever possible.

5. The end

Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
Did we miss out anything? Do leave a comment below to let us know.