Emily Stamey

Developer & Human. Finding my voice.

Page 2 of 2

Bootstrapping the CodeIgniter App, Part Two

Acceptance Testing

At the end of Part One, we were creating a lot of acceptance tests.  We had a pretty antiquated HTML form for the students to fill in a lot of data, some of which we didn’t need to collect from them.  We knew the templates would be changed and had a designer’s help making those look better and sensible.  We knew what data we needed to keep collecting in the application, so our Codeception tests checked that imaginary student’s application had the same information.  We planned knowing that the User Interface was changing and tried to ensure the data integrity.  Codeception tests are pretty brittle when you have to link to a specific DOM element, but we did the best we could to ensure that data wasn’t left off the Student’s Application for Scholarships.

Bindings

As we began writing the new code, we needed to bind those namespaces to the CodeIgniter application, so the new code could be linked within the application.

We created /app/bindings.php

<?php

use ScholarshipsSelectionInfrastructureStorageHybridSourcedScholarshipRepository;

$container['ScholarshipsSelectionDomainScholarshipScholarshipRepository'] = function($c) {
    return new HybridSourcedScholarshipRepository(
        $c['ScholarshipsSupportEventsEventStore'],
        $c['database'],
        $c['ScholarshipsCommonServicesDepartmentsService'],
        $c['ScholarshipsCommonServicesResidenciesService'],
        $c['ScholarshipsCommonServicesAcademicPlansService'],
        $c['ScholarshipsSelectionDomainCollaborationsService']
); };

The bindings file is used for most of our new functionality in the /src path.  For example, the HybridSourcedScholarshipRepository builds all the current Scholarships with information from our database tables and our Events.  The constructor requires objects of type EventStore, Database, DepartmentsService, ResidenciesService, AcademicPlansService, and CollaborationsService.  We give the paths to these in the bindings for the container ScholarshipRepository.  The container can then be included in the Selection controller.

In /app/services.php, we included the bindings and facades:

/**
 * Facade registration.
 */
Facade::setFacadeContainer($container);
class_alias('ScholarshipsSupportFacadesRequest', 'Request');
class_alias('ScholarshipsSupportFacadesDB', 'DB');
class_alias('ScholarshipsSupportFacadesLog', 'Log');

// Bring in application-specific bindings require_once('bindings.php');

Then we created a new file called /src/CowboyBridge.php, which was used to initialize the Pimple Container.

<?php

namespace CodeceptionModule;

use CodeceptionModule;

class CowboyBridge extends Module
{
    /**
     * @var PimpleContainer
     */
    private $container;

    public function _initialize()
    {
        require_once(__DIR__ . '/../app/services.php');
        $this->container = $container;
        $this->debug("Loaded container.");
    }

    public function getContainer()
    {
        return $this->container;
    }
}

Controllers

Now we needed to be able to see the new code in our controllers.  This means, for example, ,being able to pass our collection of available Scholarships to the Selection controller, and from the controller into the views.  We named our new selection controller Selectionnext in order to leave the old Selection controller intact.

class Selectionnext extends BaseController
{
    public function Selectionnext()
    {
        parent::BaseController();

        $this->scholarshipRepository = $this->container['ScholarshipsSelectionDomainScholarshipScholarshipRepository'];
    }
protected function scholarshipsDashboard($scholarshipId)
{
    $committeeMember = $this->getCommitteeMember();

    $scholDetails = $this->getScholarshipDashboard($scholarshipId);

    $this->render('pages/scholarship-details.twig', array("scholarship" => $scholDetails)));
}


private function getScholarshipDashboard($scholarshipId,$keepItLight=false)
{
 $committeeMember = $this->getCommitteeMember();

 $presenter = new ScholarshipDashboardPresenter(
 $committeeMember,
 ScholarshipId::fromString($scholarshipId),
 $this->events,
 $this->scholarshipRepository,
 $this->container['ScholarshipsSelectionDomainApplicantQueryService']
 );

 $scholDetails = $presenter->asArrayForJson();
 $scholDetails['json_string'] = json_encode($scholDetails);

 return $scholDetails;
}

I have tried to remove some of the complexity of this part and hopefully not removed anything critical.  We compiled a lot more information into our $scholDetails and sent many more variables to our views.  But this should show a bit of how we mapped the information into the Controllers of CodeIgniter.

Views

Lastly, we changed our views.  Leaving the old views in the /app/views directory as they were in CodeIgniter, we opted to use Twig views for our new interfaces, and we put those files in the /app/templates directory.    We set these paths in our app/config.php

return array( 
  ...
 'twig' => array(
   'template_path' => array(
     __DIR__ . '/templates',
     __DIR__ . '/templates/dashboard',
   )
 ),

  ...
)

In the file app/services.php we pick up these configured paths and pull them into CodeIgniter.

$container['twig'] = function ($c) {
    $loader = new Twig_Loader_Filesystem($c['config']['twig']['template_path']);

    $inDevelopment = $_SERVER['APP_ENV'] === 'development';

    $twig = new Twig_Environment($loader, array('debug' => $inDevelopment));

    $app = $c['config']['app'];
    if ($inDevelopment) {
        $app['debug'] = TRUE;
    }

    $twig->addGlobal('app', $app);
    $twig->addGlobal('notice', $c['config']['notice']);

    $twig->addFunction(new Twig_SimpleFunction('route', function($path) {
        return site_url($path);
    }));

    $twig->addFunction(new Twig_SimpleFunction('asset', function($path) {
        return base_url() . 'public/' . $path;
    }));

    $twig->addFunction( new Twig_SimpleFunction('flash_notice', function() {
        if (isset($_SESSION['flash_notice'])) {
            $_SESSION['old_flash_notice'] = $_SESSION['flash_notice'];
            unset($_SESSION['flash_notice']);
        }

        return isset($_SESSION['old_flash_notice']) ? $_SESSION['old_flash_notice'] : array();
    }));

    if ($inDevelopment) {
        $twig->addExtension(new Twig_Extension_Debug());
    }

    $twig->addFunction( new Twig_SimpleFunction('flash_exists', function() {
        return !empty($_SESSION['flash_notice']);
    }));

    return $twig;
};

The $_SERVER['APP_ENV'] variable was set in our .htaccess file.  This Twig configuration allows us to get debug information in our development environments.  We added two simple functions to build our asset path and our route path.  This meant we could use route() and asset() in our templates to correct paths across environments.  There are also simple functions to determine whether there are existing flash messages to pass into the template.

Conclusion

This code grew over a long period along with the new functionality of our application.  If you have questions about something that seems missing, please feel free to ask in comments.  I may be able to include a little more code to clarify the details.  Our Scholarships application is pretty complicated, and I’ve tried to skim a lot of that detail out of the code examples in order to simplify and focus on the bootstrapping.  I hope that it has been useful to you because it was really useful for me to re-examine how this all ended up working together.

Bootstrapping the CodeIgniter App, Part One

I have worked on this Scholarships project for about two and a half years.  It’s going to be replaced by another application, so I have reviewed how we did this and what I’ve learned in the process.  Modernizing a CodeIgniter Application – The Problems discusses the problems we were trying to solve (TLDR; we had a legacy CodeIgniter application with a giant App model full of functions making DB calls).  This post shares how we bootstrapped the CodeIgniter application to allow us to bring new code online without breaking the pre-existing application.  The reason we had to do this is also described in the previous post.

It’s important to me that I mention my coworker, Dustin Wheeler, figured out how to do most of this, and I have also learned a lot from Mitch Amiano during this project.  I am trying to document the ways that we modernized this Application to make sure that I am able to do it again.  Most of my development life has involved taking on existing applications, so this seems like a useful bit of information.

Screen Shot of Early Scholarships Working Tree

Screen Shot of Early Scholarships Working Tree

This is what the tree basically looked like at the beginning:

The directories /_data/app, /dinner, and /public already existed.  The bulk of the Application existed in the app directory.  Dinner was another little application on the side.

The first steps included creating a composer.json file that named the application, set the default namespace and mapped that to a new directory called /src.

The initial composer.json configuration file.

Initial composer.json file

 

 

 

Next we installed Phinx for database migrations and PHPUnit and Codeception for tests.  After the bootstrapping process, we used Codeception acceptance tests to verify that the data displayed on the Student Application stayed the same when we built entirely new views and changed the workflow around how the students applied for Scholarships.

Configuration

In index.php, we turned on error_reporting and required the composer autoloader.

If no file_exists vendor/autoload.php, throw an exception. Otherwise require vendor/autoload.php

Adding composer autoloader to index.php

Next we had a few fixes to CodeIgniter bugs.  We removed a call to set_magic_quotes_runtime() in the file /_data/system/codeigniter/CodeIgniter.php.  In another file /_data/system/codeigniter/Common.php we removed the & from the following statement: $objects[$class] =& new $name();

We built two .sql files for the two databases used by our application.  In these files we saved the create schemas for each of the databases from Production. These files were later populated with anonymized test data, since we couldn’t use anything personally identifiable about our students or faculty.  We kept most of the scholarship data the same, so we could test against real scholarship matching criteria, but we anonymized the contact info in those as well.

We created a debug controller that later went away.  I’ll come back to note its purpose.  I believe it was to test new code from /src being pulled in.

The database configuration had persistent connections turned on, and we set them false:

$db['default']['pconnect'] = false;

$db['default']['db_debug'] = false;

$db['default']['cache_on'] = false;

A base database configuration script became pretty useful for three developers.  It began as a deploy script, but later evolved into a fully incorporated configuration file.  In the same file as above, the /app/config/database.php, we anonymized the hostname, username, password, and database to things like DB_HOST,  DB_USERNAME, DB_PASSWORD,  and DB_NAME.  The deploy script let us set these to something real in our development environment.  I have pasted the bulk of that script, but this script will only configure one database.  It seemed more readable and shorter this way.

#!/bin/bash

########################################################
# Start Application Configuration
########################################################
if [[-f app/config/config.php ]]
then
        echo "Existing Application Config:"
        GREP "APP_" app.config.config.php
fi

APP_BASE_URL="http://localhost:8080/"
APP_INDEX_PAGE="index.php"

echo "Configure Application Config (1/1):"
read -p "Application Base URL ($APP_BASE_URL): " base_url
read -p "Application Index Page ($APP_INDEX_PAGE): " app_index_page

APP_BASE_URL=${base_url:-$APP_BASE_URL}
APP_INDEX_PAGE=${app_index_page:-$APP_INDEX_PAGE}

sed "
    s/APP_BASE_URL/$APP_BASE_URL/g;
    s/APP_INDEX_PAGE/$APP_INDEX_PAGE/g;
" app/config/config.default.php > app/config/config.php

echo "Rewrote app/config/config.php"

########################################################
# Start Database Configuration
########################################################

if [[ -f app/config/database.php ]]
then
    echo "Existing Config:"
    grep "$db" app/config/database.php
fi

# Default Configuration Values
DB_HOST="localhost"
DB_NAME="scholarship"
DB_USERNAME="root"
DB_PASSWORD=""

echo "Configuring Scholarship Database (1/2):"
read -p "DB Username ($DB_USERNAME):" username
read -p "DB Password ($DB_PASSWORD):" password
read -p "DB HOST ($DB_HOST):" dbhost
read -p "DB Name ($DB_NAME):" dbname

DB_USERNAME=${username:-$DB_USERNAME}
DB_PASSWORD=${password:-$DB_PASSWORD}
DB_HOST=${dbhost:-$DB_HOST}
DB_NAME=${dbname:-$DB_NAME}


sed "
    s/DB_USERNAME/$DB_USERNAME/g;
    s/DB_PASSWORD/$DB_PASSWORD/g;
    s/DB_HOST/$DB_HOST/g;
    s/DB_NAME/$DB_NAME/g;

" app/config/database.default.php > app/config/database.php

echo "Rewrote app/config/database.php"
sed -i "
    s/DB_USERNAME/$DB_USERNAME/g;
    s/DB_PASSWORD/$DB_PASSWORD/g;
    s/DB_HOST/$DB_HOST/g;
    s/DB_NAME/$DB_NAME/g;
" app/config/config.php

echo "Updated app/config/config.php because stupid junk."

########################################################
# Import base schemas for databases.
# Should kick of migrations in future.
########################################################

# Import schema for default database.
mysql -u ${DB_USERNAME} -p${DB_PASSWORD} -h ${DB_HOST} < database/seeds/default.sql

Modifying CodeIgniter to Allow Testing

In the file /_data/system/libraries/Loader.php, we removed the line from function CI_Loader():

global $OUT;

with the following line:

$OUT =& load_class('Output');

In the file /app/config/config.php we set $config[‘enable_hooks’] to TRUE.

In the file /app/config/hooks.php we added this hook:

$hook['display_override'] = array(
    'class' => 'DisplayHook',
    'function' => 'captureOutput',
    'filename' => 'DisplayHook.php',
    'filepath' => 'hooks'
);

I’m pretty sure that hook is for Codeception to capture output using PhantomJS.  At this point, we began with a new Codeception test suite for the Student Application.  This part of our Application was mostly changing visually.  When a student completed their application and submitted the information, we created a StudentSubmittedApplication event instead of saving an entire set of data in a database row, as the previous application was working.  But this is getting a little ahead of the game.  We’re bootstrapping here.

In the file /app/hooks/DisplayHook.php, we told it to get the APP_ENV variable

<?php
// application/hooks/DisplayHook.php
class DisplayHook {
    public function captureOutput() {
        $this->CI =& get_instance();

        $output = $this->CI->output->get_output();

        if (getenv('APP_ENV') != 'testing') {
            echo $output;

            if(getenv('APP_ENV') != 'production') {
                if ($this->requestIsNotAjax()) {
                    echo sprintf(
                        '<img id="debug-overlay" src="%spublic/images/debug-overlay.png" /><style>#debug-overlay { position:fixed; top:0; left:0; z-index:-1; width:900px; opacity:0.25; }</style>',
                        base_url()
                    );
                }
            }
        }
    }

    private function requestIsNotAjax()
    {
        return  !(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest");
    }
}

We set this value in a .htaccess file for Apache:

SetEnv APP_ENV development

At this point, we were writing a lot of tests because the existing application had none, and the student application was being redesigned.  There is a lot more to describe here, but I’ve got to parse through a lot of UI changes to find the useful bits.  I’m going post this as a Part One.  Part Two will include Pimple containers and bindings, controller actions to reach new code in /src, and other fun stuff.  Please feel free to post questions.  I would like to keep this as useful as possible.

So you want to be a programmer…

I recently heard this anecdote.  It’s sticking with me, so I’m sharing it!

So!  You want to become a programmer.  Well, here’s a list of languages for you to learn:

Ruby, NodeJS, ASP, PHP, Java, Python, AngularJS, …

Choose one of these as the language you know the best and build your career on.  Now, look at the remaining languages in the list and choose one.  From this point forward, this will be the language you hate.  You don’t need a reason to hate this language, but you can never be convinced to appreciate or use it.  Once in a while you will hear another person hate the same language as you.  They may have a reason, which you can add to your list of reasons for hate without needing to research the validity of that person’s reason.

Does this sound familiar?

Celebrating Accomplishments

Lately I’m thinking about my accomplishments this year in tech.  I feel much more a part of the greater development community than I ever have before.  I owe a lot of that to my Co-Organizing the TrianglePHP meetup group and my TA-ing with Girl Develop It.  I have also overcome some of my hesitation to contribute code in Open Source again.

Read More

Modernizing a CodeIgniter Application – The Problems

When I took my current job, I was assigned a specific project that supported the College’s distribution of Scholarship money to students.  This application had many errors and needed additional functionality.  Primarily, it needed to:

  1. handle students with more than one major
  2. reliably match students to Scholarship criteria
  3. allow the selection committee to give awards within in the application

This was a pretty tall order because the application was fairly large.  The bulk of functionality was within a single App model with functions that made SQL queries to the database.

Read More

Inspiring Kids with Technology

This week I had the pleasure of attending All Things Open, which is always a restorative, inspiring experience for me!  I love meeting the people, and my favorite thing of all is to learn how others are innovating with Open Source.  It is the main reason I use Open Source and a cause I heartily believe in.  I often wish that I was doing more good with my open source skills and All Things Open shows me ways that I can help!

My favorite talk last year was by Charlie Reisinger at Penn Manor talking about the Open Source classroom.  He told us about how they had open sourced their classrooms at the local hospital and given a Linux-powered laptop to every student.  Students and Faculty worked on the Linux environments that were necessary after consulting with teachers about what their needs might be and including those tools in the software package. Laptops backed up remotely to prevent data loss, and the students were given root level access to make changes as they saw fit.  In addition to all of this, students were the driving force of the help desk.  They supported fellow students and were free to learn and innovate.  This program was a huge source of pride and accomplishment for everyone involved!

Read More

Going from Procedural PHP to Modern PHP

I have spent a lot of time over the last few years trying to figure out what is the right way to transition from procedural PHP code to Modern PHP best practices.  It doesn’t seem like it should be the painful, gut-wrenching process as it was for me.  Now the question becomes stronger because I want to help others make that switch, and I don’t want the difficulties to be deal-breakers.  I want to remove the obstacles of prerequisite knowledge but planning things in the simplest order.  However, it seems like you have to know many things all at once to make the transition.  The simpler it is to learn, the more easily I can convince others to join me on this journey.  It makes it easier for their management to agree to it.  But how do I teach it?

I contributed!

I made my first non-documentation open source contribution on Github today.  I created an account on packagist to hold it even.  Although it doesn’t show up there yet.

Screen Shot 2015-08-19 at 12.14.46 AM

 

As fun as this little command will be in future chats on irc, it has been a challenge to get some characters upside down, especially the elusive B.  I need to add more punctuation in the next revision, but for now, I’m going to bed.

Why I like gathering PHP Women at conferences

Sometimes I feel like a bit of a “bad guy” for saying, “Hey, PHP Women!  Let’s eat together!”  But then I have such a great experience doing it, and it’s so positive. I will definitely do it again.  I don’t do it to be mean to men in the industry.  Let me be clear, we are not getting together to talk about men in the industry or even women in the industry.  We just talk about work and life, and it is awesome.  It’s relaxed.  For one meal we are flipping the table on the traditional ratio at conferences, at our jobs, and just being ourselves.  In that one little lunch, I let my guard drop.  It’s a guard that I have grown very accustomed to having up at work.  It is a shield that I use to “not be so sensitive” and it “translates” some types of interactions that I would normally be bothered by.

Read More

Page 2 of 2

Powered by WordPress & Theme by Anders Norén