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…..

Advertisements

Don’t fear the dev

It’s amazing to notice that so many people are still afraid of us, developers. This includes our clients and the businesses. I will address the case of most of our clients in this post. Before diving into the subject let me explain myself. I mean by afraid the fact that client still believes in a few facts on us:

  • Expensive
  • Uncontrollable
  • Wizardry
  • Truant
  • Less trustworthy

And this list continues so so many other suspicious faces.

When a client manages to order a service from you and decides to hide. You should know that he’s running from you for some of these reasons. This behavior goes against the Agile Software Development principles. The Agile Manifesto suggest a people-centric approach. One of its core values is to focus on customer collaboration over contract negotiation. Instead of having just a deal sealed with a client you stay in touch more often. This leads us to the fourth core value of that same manifesto: responding to change over following a plan.

All this makes sense since the client will have the opportunity to follow up on every little step of the job. He can rectify any inaccuracy on the project specs. This avoids the developers from building and breaking down and thus saving time.

Based on my personal experience, I tend to build better when my client is collaborative. A client who follows up his project helps build a great tool. This can be applied to designing as well. In fact, this is the best field to applied agility.

Being agile provides several advantages to the developer, the client, and allows to build good products. Here are some of the benefits:

  • Less struggle to get started
  • Strong products
  • Sustainable development process
  • Stable code base and product
  • Time saving
  • High fidelity results
  • Predictable cost

This actually shows how useful it’s to keep in touch with your developers rather than running from them. Thinking that can save you will actually make you loose more.

As a developer or a designer, you should also know that it’s imperative for you to listen to your client often. This will help you to avoid doing things and coming back over and over again.

The point here is to save time and cost. Your client is the right person to tell you what exactly to do and how to do it. Don’t play the super-hero. Be the dump, follow the instruction and you will make happy clients.

From : PHPOCEAN


Can I Use Popular Framework Features Without a Framework?

If you’ve been wondering about this question, the answer is YES!

There are many tools and libraries in the PHP ecosystem that we can use when developing an application. Some of them are grouped in frameworks which provide us some preconfigured structure. But with such variety of tools, we can easily make our own structure according to our needs.

In this article I will take a look and list some popular libraries for the different technical needs of our applications, such as talking to the database, routing, providing output to the web and etc.

PHP, frameworks,

But first, let’s get back to basics and explain what a framework is.

According to the general definition:

Framework is a universal, reusable software platform to develop software applications, products and solutions. To simplify, it is kind of library, piece of software which provides web developers with code base and consistent, standardized ways of creating web applications.

Your project will have to choose from tons of PHP libraries, frameworks and components. In addition, there are many PHP libraries, frameworks and components to adopt from. And these are called project dependencies like Composer and PEAR. Until recently PHP didn’t find acceptable way to manage these project dependencies. Some of the dependencies explained below show how can you use PHP without frameworks.

  • Composer repositories like Composer, PEAR, VSC

A dependency manager which installs packages locally with package description and name and version. In basics, package is just a directory containing something. In this case, it is a PHP code, but in theory it could be anything.

Repository is a package source. Practically it is a list of packages/versions. The composer will search in all your repositories to find the packages your project requires.

  • Databases like MySQL, PostgreSQL, NoSQL

There will be times when your PHP code will use database to persist information and there are few options to connect and interact with your database.

  • Object-relational mapping (ORM) like Doctrine, Readbean, Eloquent

The ORM manages the translation of object into relational databases and vice-versa. This creates so-called “virtual object database” which can be used from within the programming language.

  • Templating like Twig, Blade, Mustache, Plain PHP Templates

Templates provide convenient way of separating the controller and domain logic from your presentation logic. They typically contain the HTML of the application, but may be also used for other formats such as XML. Templates are often referred to as “views” which make up part of the second component of the model-view-controller (MVC) software architecture pattern.

  • HTTP like Guzzle, Buzz, HTTPFul, Requests

This is protocol destined for sending documents back and forth over the World Wide Web. A protocol is a set of rules that is used to identify which messages can be transferred and which are suitable answers to other queries.

  • Mailers like PHPMailer, SwiftMailer, Stampie

Mailers are libraries used in order to give the application an ability to send mails.

  • File Systems like Gaufrette, Flysystem, CSV

Libraries for file manipulation and MIME (Multipurpose Internet Mail Extensions) type detection.

  • Testing like PHP Spec, PHP Unit

Writing automated tests for your PHP code is considered to be a best practice and can lead to well-build applications. Automated tests are a great tool for making sure your application does not break when you are making changes or adding new functionality and should not be ignored.

PHP, code, frameworks

However some of the dependencies will not be used by your application and may not be essential, therefore you can easily create your own PHP project containing custom dependencies that are most suitable for the project.

To sum up, using framework can bring to faster development as it tries to save your work by make you define an overly complex configuration that has to accommodate every possible use case.

The Best Way to Learn PHP

Learning something from scratch is almost always an arduous affair — you simply have no idea as to where to start, or not to start, to kick things off. I loathed learning about the idiosyncrasies of C++’s syntax when all I wanted to learn were some darn programming concepts. As I’m sure you can agree, this is a less than ideal situation.

This is where the Nettuts+ “The Best Way to Learn” series comes into the picture. This series is intended to be your blueprint, your road map, your plan of action for learning your topic of choice! You don’t have to worry about finding the best resources, sorting out the bad ones, and figuring out what to learn next. It’s all here. Just follow it, step by step.

Today, we’re going to figure out the best way to learn PHP.

If you need immediate help, try working with one of the experienced PHP developers on Envato Studio. They can fix PHP errors, add features, or even create new apps for you.

PHP developers on Envato Studio
PHP developers on Envato Studio

If you’re reading this, chances are that you’ve Googled a lot to decide which language to learn and how. And without a doubt, you must have run into a ton of articles about how language X is so much better than PHP – and PHP is going to die through obscurity soon.

Haters gonna hate!

As the popular saying goes, haters gonna hate! PHP has been at the helm of the web as you know it and that’s for a very good reason. It’s a mature language, has excellent documentation and a massive number of learning resources along with a great variety of utilities built around it.

And let’s not forget the sheer proliferation of hosts and frameworks PHP has spawned. Like Heroku like hosting? Don’t worry, there are a number of excellent options for PHP as well!

Tut image

You could just install PHP but it gets quite boring without a server and some sort of database to play around with. And as a beginner, it’s not really trivial work to get all of these installed and configure each to work with the others without issue.

This is where you grab a package such as XAMPP. These life savers typically install Apache, your web server, along with mySQL, a database system along with PHP significantly cutting down on set up time.

Bonus points if you’re the code monkey type and install everything by hand.

You can also try LAMP, WAMP…….

Before I send you off to alternate sources for PHP enlightenment, let me first refer you to our very own series for absolute beginners from none other than your favorite editor, Jeffrey Way.

In this series, over the course of 40+ screencasts, everything from installing PHP to variables, from functions to working with MySQL is covered.

For learning basics, w3schools can be a great place. try it……..

Tut image

Khan Academy may sound like an odd choice since there are no PHP lessons in there but trust me, it’s a good choice. What you can’t find in pure PHP, you can find in the basic of programming. For example, if you’re new to the entire programming hoopla, this is a great place to start.

Another great place to start is Lynda. Here at Envato we have immense respect for those teaching there — the content is usually top notch and cover their topics well. And they cover a vast range of topics as well. If you need a specific lesson, this is where you should begin.

The videos should give you an very good springboard, but, hopefully, hungry for more knowledge. The below books should give you a more elaborate introduction and lots of varied topics for you to devour.

If you feel bored reading the initial portions, good, just skip ahead to the portions where your head hurts.

Nettuts image

Author: David Powers

“So why another PHP book? Well, not everyone who uses PHP is a programmer. PHP is the most common dynamic web language used by designers, if their web sites require dynamic functionality, and there are hordes of novice users who want to set up dynamic web sites.”

Nettuts image

Author: Jason Lengstorf

“PHP for Absolute Beginners starts at the very beginning stages of web programming, showing even the most inexperienced web developer, through examples, how to build a basic content management system. The book dives directly into writing web applications with accompanying explanation rather than explaining elements of the language and then showing examples.”

Nettuts image

Author: Adam Trachtenberg

“PHP Cookbook has a wealth of solutions for problems that you’ll face regularly. With topics that range from beginner questions to advanced web programming techniques, this guide contains practical examples — or “recipes” — for anyone who uses this scripting language to generate dynamic web content.”

This is the perfect time to build something simple with your new found knowledge.

Alright! With all those information swirling inside, you should feel like a rockstar. If not, don’t worry, it’s completely normal. Talk to me later so we can share notes about how daft we feel.

This is the perfect time to try and build something simple with your new found knowledge. It’s best to not try to build something too complicated and fail though — it’s a lot more disheartening than you’d think. Imagine being rejected for the first time. Now multiply it by a few hundred and you’ll be close.

Since you’re just starting out, play it safe and build something absolutely basic like a CRUD app. Nothing major — a few inputs and an ‘uncool’ table to display saved results. This tiny exercise will test your knowledge of a lot of PHP basics including the much vaunted ‘interfacing with a database’ skill.

Feeling better now? You should! You gazed upon where there was naught and said ‘This won’t do!’ and created something from scratch. If it were me, I’d be pumped. Let’s use it to extend our knowledge a little more.

While a simple CRUD app is a great start, you’d ideally need more complicated. A simple login/user system is absolutely great for this.

You get to learn how sessions work, how basic authentication is done, how to implement basic security measure and a ton more.

Note: If you’re in need of a little guidance, start here.

Tut image

At this point, after creating a non-trivial system, you probably have noticed how repetitive some of the work is. Why the heck do you need to write your own sessions class or work on hashing passwords yourself? The answer, my friends, is to go with a lightweight framework.

A framework abstracts a lot of the repetitive, boilerplate features in your typical application thus freeing up your brain to actually getting things done.

Note: CodeIgniter, a very lightweight, yet powerful framework. If you prefer Kohana, we do that too!

Tut image

Now that you’ve been with a lightweight framework, you can now check out the alternate path — a full stack framework. A full stack framework typically ships with a lot more features including code generators, ORMs and an inbuilt server. An excellent choice would be CakePHP — the PHP equivalent of Rails.

The reason you need to check these out later is because there is a lot of ‘magic’ going on. Without a solid understanding of how lightweight frameworks work, it’s hard to really dig into the better featured ones since you’ll mostly be lost and won’t understand how things work.

Note: I recommends both FuelPHP and Laravel as top-notch, modern PHP frameworks.

 

With all that information behind you, giving you Indiana’s swagger, now is the time to build something truly awesome. This is the final destination for PHP nirvana — and the choice is up to you.

So what exactly should you be building? Here are a few ideas:

  • A blog is always a safe option. There are a ton of open source solutions for you to get inspiration for the software architecture and the functionality requirements are unambiguous.
  • It’s a little old school but a discussion board is another excellent choice. Moderator rights and post counts, ahoy! If you need a little guidance, this tutorial is a great place to start.
  • Or if you’re too hip for any of these, build yourself a project management application or even just a todo list. They’re always fun to build and you’ll almost always end up using it personally.

Of course, there are just suggestions. No one is stopping you from building a multi-user, realtime chatroom or a service which receives input from random internet strangers and lights up stuff in your room. No one’s judging, go crazy!

Development is as much about the workflow as much as it is about the code.

Development is as much about the workflow as much as it is about the code. Recently, a typical developer’s workflow has been massively improved by version control as well as platform as a service solutions.

Version control, as expected, frees you up from having to manage revisions manually while PaaS solutions save you from having to do a lot of sys admin work just to get your app to scale.

You can getting started with Git.

New techniques and tools are being introduced everyday.

The web development industry is rarely in a state of equilibrium — everything is changing all the time. New techniques and tools are being introduced everyday and it’s important that you not only read about them but also start contributing.

Find a little glitch in some framework? Submit a patch. Added some new functionality? Patch away! These not only earn you good karma but also valuable points on your resume.

And, oh, about the keeping up to date stuff? Subscribe to our feed and follow us  and I promise you’ll know all you need to know!

Tryruby

Even though that you are a master of the PHP domain, you can’t afford to, or shouldn’t, rest. PHP is a grand language but that doesn’t mean that it does absolutely everything perfectly.

There is an ever increasing number of new languages out there each adding their own spin to solving a very specific problem that you simply can’t afford to miss out on. And learning something new something doesn’t really wipe out knowledge gained earlier does it? Well, except Star Wars, of course. Those new movies were a crapshoot.

Ruby, Python and Clojure are some of the languages that I’m constantly amazed by and I think they deserve your attention as well. Neither of these languages are necessarily ‘better’ than PHP but each of them do things their own unique way and you owe yourself a chance to take a look and find out whether that approach is for you.

Well, this is the end of the road, partner! Hopefully, this plan can help you become a PHP master and, indeed, take over the world.

If you feel that I’m missing some obvious resources here, feel free to yell at me in the comments section below and I’ll update this article whilst crying silently. Thank you so much for reading!

Top 10 web development trends in 2017

USING AI TO CREATE WEBSITES

Artificial intelligence programs are already used successfully by Google and Wikipedia, the technology is more than within our grasp to allow us to develop software which can think and act as a human without requiring the manpower. One of their most prolific uses already is for web design programs, such as The Grid, which allows amateurs to produce some pretty slick websites by using an artificial intelligence program named Molly.

SITE GENERATORS

The reason we believe that the popularity of static site generators keeps going up is simple. Static site generators are a great way to create websites. You don’t need a database, instead your web pages are simple files which run on your servers. With that comes advantages in website loading times, better security handling, and ease of deployment.

BOTS & THE ROLE OF CONVERSATIONAL UI

Bots are there to make our life easier and our experiences more personable (or at least they should). Bots are interesting from various standpoints and use cases.design and development of conversational UI will become an important topic for developers in 2017. JAVASCRIPT IN 2017 It is by far the most popular technology used by full stack developers.

MOTION UI

With 36% (or 2382 votes) you stated that this was the most important development trend in 2016. The newest version of Motion UI works through flexible CSS patterns with all kinds of. Real time notification This used to only be embraced by chat applications. It not the case anymore, even revenue visualization dashboards need to update in real-time.This has been necessitated by the fact that most applications in 2017 support multiple point access, so the other party needs to know what’s currently the state of things before they make decisions.

Modular Design

There are a lot of libraries and frameworks both for the front end and back end that ensure that the components of an application are not completely tied into one another.

Live Support

Even a blog nowadays has that little form at the bottom right corner labeled Chat with us! More businesses are throwing their weight behind the need for live interaction as opposed to back and forth email communication with potential customers in 2017.The good this is that there are already a handful of companies offering this service through copy/paste so you wont have to build it ground up in most cases as a web developer – unless for some reason your client/company requires you to.

Single Page Application Design

If you submit a login form today and you have to wait for another 10 seconds for the page to reload then it comes with the message, “Invalid password!” you pretty much start getting irritated, right? Yes, because a lot of this stuff can be done when you are on the same without reloading or taking you to another page. It just saves times and serves for a greater user experience..

HTML compression

It is not just about HTML. JavaScript and CSS are also being compression but this practice has been around for close to a decade or even more. Web developers in 2017 are really looking into what options they have with HTML compression libraries. Also remember a couple of points like :

• Javascript is the future. People are going away from tight integration of server-side code for generating html.

• JQuery will be out of market soon. It is going to be interesting to see how legacy code will be handled on the way.

• ES6 Component based, and class like javascript is providing a new paradigm to the way we see front end development.

Clean Code Concepts Adapted for PHP

Clean Code PHP (jupeter/clean-code-php), is a guide based on the book Clean Code: A Handbook of Agile Software Craftmanship, a classic programming book about writing maintainable code by Uncle Bob Martin.

The clean-code-php guide is inspired by a JavaScript adaptation, clean-code-javascript with PHP-specific features.

Here are a few of my favorite adaptations from the clean-code-php repository:

Don’t add unneeded context

Bad

<?php

class Car
{
    public $carMake;
    public $carModel;
    public $carColor;

    //...
}

Good

<?php

class Car
{
    public $make;
    public $model;
    public $color;

    //...
}

View Don’t add unneeded context in the guide.

Function Arguments (2 or fewer ideally)

Bad

<?php

function createMenu($title, $body, $buttonText, $cancellable) {
    // ...
}

Good

<?php

class MenuConfig
{
    public $title;
    public $body;
    public $buttonText;
    public $cancellable = false;
}

$config = new MenuConfig();
$config->title = 'Foo';
$config->body = 'Bar';
$config->buttonText = 'Baz';
$config->cancellable = true;

function createMenu(MenuConfig $config) {
    // ...
}

View Function Arguments in the guide.

Functions Should Do One Thing

Bad

<?php

function emailClients($clients) {
    foreach ($clients as $client) {
        $clientRecord = $db->find($client);
        if ($clientRecord->isActive()) {
            email($client);
        }
    }
}

Good

function emailClients($clients) {
    $activeClients = activeClients($clients);
    array_walk($activeClients, 'email');
}

function activeClients($clients) {
    return array_filter($clients, 'isClientActive');
}

function isClientActive($client) {
    $clientRecord = $db->find($client);
    return $clientRecord->isActive();
}

View View Functions Should Do One Thing in the guide.

Opinions, Opinions, Opinions

The author outlines the following about the purpose of the guide:

Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.

In a dynamic language like PHP (or any language for that matter), developers will disagree with some (or many) of the points made about the concepts demonstrated. I think the point I’d make is not to write off all ideas contained in the guide if you disagree with one or more ideas.

Learn More about Clean Code

I highly recommend that you read the Clean Code book to get a deeper understanding of the guidelines demonstrated in the PHP adaptation. On its own, the PHP guide is a good read, but part of the journey is learning how to spot code that needs some work and then adapting it.

Another great book related to Clean Code, is The Clean Coder: A Code of Conduct for Professional Programmers which focuses on you, the coder. In my opinion, these two books should be a must-read for programmers of any experience level looking to improve their code craftsmanship.

RFS: the automated approach for responsive font sizes

Mastering responsive font sizes for websites has never been easy. Especially for bigger font sizes, multiple breakpoints were needed to gain a little control over the behaviour on all screen sizes. Some improvements were made when calc-functions were introduced to calculate a font size, but still there was no automated way to control all your font sizes for all possible screen widths. That has now changed.

RFS to the rescue

RFS is a SCSS-mixin which generates the responsive css for you.

RFS stands for Responsive Font-Size, easy to remember, easy to use. It’s a desktop-first approach which automatically calculates the correct font size for every screen width. Desktop-first approach means you just have got to define your font-size for big screens and the font size will automatically decrease for smaller ones.

The main advantages of using RFS

  • Font sizes will rescale for every screen width, this prevents long words from being chopped off the screen
  • Super easy to use, no need to define complex configurations for each font-size
  • Font sizes of all text elements will always remain in relation with each other
  • Rem-based font sizes will allow the user to change his default font size in his browser. People with limited vision can therefore increase their font size to increase readability.

With or without RFS

In the example below, you’ll see the difference between a website with and without RFS. The on the left image shows the default bootstrap implementation. In this case smaller words are used (Hello world), but in real life we commonly come across longer words which would be chopped off of the screen. Using RFS, all text elements are scaled correctly, which prevents unwanted behaviour.

Without RFS With RFS
 without-rfs-1.png  with-rfs-1.png

Video-demo of the problem and RFS’s solution

In the first part this video shows the default bootstrap implementation, in the second part RFS takes care of the responsive rescaling of the text.

How does it work?

RFS splits the calculation of the font-size in 2:

  • 1 static font size for bigger screens
  • 1 adaptive font size which decreases along with the screen width of your browser. This font size is calculated in a media query with css’s calc-function.

There are some configuration variables which can influence the font size’s decreasing.

To the code

This input (SCSS):

.title {
@include rfs(60);
}

 

Will generate this (CSS):

.title {
font-size: 3.75rem;
}

@media (max-width: 1200px) {
.title {
font-size: calc(1.35rem + 3.2vw);
}
}

Further on, we will explain how these numbers are calculated.

Visualisation of RFS

Everything is easier to grasp when you can visualize it. This is what RFS’s default configuration looks like:

graph-rfs.png

The configuration in detail

There are configuration variables which influence the calculation of the font size. All variables must be set unitless in the configuration:

  • $rfs-minimum-font-size: (in px)
    Font sizes which are calculated by RFS will never be lower than this size.
    However, you can still pass a smaller font size to RFS, but then RFS won’t dynamically scale this font size. For example (see graph above): rfs(17) will trigger dynamic rescaling,  with rfs(10) it will just stay 10px all the time.
    Default value: 12
  • $rfs-minimum-font-size-unit: (string)
    The font size will be rendered in this unit. Possible units are px and rem. This setting doesn’t influence $rfs-minimum-font-size, which will always be configured in px.
    Default value: rem
  • $rfs-breakpoint: (in px)
    This where dynamic rescaling begins. Above this breakpoint, the font size will be equal to the font size you passed to the mixin.
    Default value: 1200
  • $rfs-breakpoint-unit: (string)
    The width of $rfs-breakpoint will be rendered in this unit. Possible units are pxem and rem. This setting doesn’t influence $rfs-breakpoint, which will always be configured in px.
    Default value: px
  • $rfs-factor: (number)
    This is the more complex part. If the font sizes would all resize to the same value when the screen width would be 0, there wouldn’t be a lot of difference between the font sizes on small screens. To prevent this, we brought the $rfs-factor to life.
    Let’s take an example from the graph above: The font size rfs(47) at a screen of 0px is 19px and not 16px because of this factor. This minimum font size is calculated like this:

    Calculate the difference between the font-size (47) and $rfs-minimum-font-size (12)

    47 – 12 = 35
    Divide this number by the $rfs-factor (5)
    35 / 5 = 7
    Add this number to $rfs-minimum-font-size (12)
    7 + 12 = 19

    The higher $rfs-factor, the less difference there is between font sizes on small screens. The lower $rfs-factor, the less influence RFS has, which results in bigger font sizes for small screens. If $rfs-factor is set to 1, there wouldn’t be any difference at all. 1 is the lowest possible value.
    Default value: 5

The calculation of RFS

Let’s take back our example of rfs(60). We use the default configuration:

  • $rfs-minimum-font-size: 12
  • $rfs-minimum-font-size-unit: rem
  • $rfs-breakpoint: 1200
  • $rfs-breakpoint-unit: px
  • $rfs-factor: 5

SCSS:

.title {
@include rfs(60);
}

The first part of the generated css is pretty straightforward, because $rfs-minimum-font-size-unit is rem, font-size is displayed in rem (60/16=3.75):

.title {
font-size: 3.75rem;
}

Now let’s have a look at the second part. $rfs-breakpoint is 1200px and it is rendered in px because $rfs-breakpoint-unit is px:

@media (max-width: 1200px) {
.title {
font-size: calc(1.35rem + 3.2vw);
}
}

We can calculate 1.35rem the same way we did above when explaining $rfs-factor.

Calculate the difference between the passed font-size (60) and $rfs-minimum-font-size (12)
60 – 12 = 48

Divide this number by the $rfs-factor (5)
48 / 5 = 9.6

Add this number to $rfs-minimum-font-size (12)
9.6 + 12 = 21.6

Convert this number to rem
21.6 / 16 = 1.35

Now we have a font size of 1.35rem or 21.6px below 1200px. Between a screen width of 0px and 1200px, we use vw-units to increase the font size:

Calculate the difference between the font-size at 0px and 1200px
60 – 21.6 = 38.4

Those 38.4px need to be added over 1200px
38.4 / 1200 = 0.032

The screen width = 100vw, so this number needs to be multiplied by 100
0.032 * 100 = 3.2

Tada! Now you have everything you need to construct the second part.

Demotime

We’ve set up a Codepen demo where you can test RFS and play with the configuration at: http://codepen.io/MartijnCuppens/pen/ZBjdMy. However, if you want to test an entire website, check out the Bootstrap-version:

View the bootstrap-demo with RFS

Let’s put it in bootstrap by default!

There is a feature request pending to implement RFS by default in Bootstrap. Put those thumbs up if you would like this feature to be implemented here: https://github.com/twbs/bootstrap/issues/23053

Download on github

Download the RFS-mixin here:

https://github.com/MartijnCuppens/rfs

Feedback

Let us know if you have any questions or suggestions. Just tweet to @Martijn_Cuppens.