100% found this document useful (1 vote)
19 views

Lumen Programming Guide Writing PHP Microservices REST and Web Service APIs 1st Edition Paul Redmond (Auth.) download

The document is a guide for using Lumen, a PHP micro-framework for building RESTful APIs and web services, authored by Paul Redmond. It covers installation, creating applications, error handling, and API resource management, among other topics. The guide aims to enhance developer productivity by leveraging Lumen's features alongside Laravel components.

Uploaded by

muttywuestja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
19 views

Lumen Programming Guide Writing PHP Microservices REST and Web Service APIs 1st Edition Paul Redmond (Auth.) download

The document is a guide for using Lumen, a PHP micro-framework for building RESTful APIs and web services, authored by Paul Redmond. It covers installation, creating applications, error handling, and API resource management, among other topics. The guide aims to enhance developer productivity by leveraging Lumen's features alongside Laravel components.

Uploaded by

muttywuestja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Lumen Programming Guide Writing PHP

Microservices REST and Web Service APIs 1st


Edition Paul Redmond (Auth.) pdf download

https://textbookfull.com/product/lumen-programming-guide-writing-
php-microservices-rest-and-web-service-apis-1st-edition-paul-
redmond-auth/

Download more ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

PHP Web Services APIs for the Modern Web 2nd Edition
Lorna Jane Mitchell

https://textbookfull.com/product/php-web-services-apis-for-the-
modern-web-2nd-edition-lorna-jane-mitchell/

Integrating Web Services with OAuth and PHP A php


architect Guide 1st Edition Matthew Frost

https://textbookfull.com/product/integrating-web-services-with-
oauth-and-php-a-php-architect-guide-1st-edition-matthew-frost/

PHP 8 Quick Scripting Reference A Pocket Guide to PHP


Web Scripting Third Edition Mikael Olsson

https://textbookfull.com/product/php-8-quick-scripting-reference-
a-pocket-guide-to-php-web-scripting-third-edition-mikael-olsson/

PHP for the Web Visual QuickStart Guide 5th Edition


Larry Ullman

https://textbookfull.com/product/php-for-the-web-visual-
quickstart-guide-5th-edition-larry-ullman/
Designing Web APIs Building APIs That Developers Love
First Edition Jin

https://textbookfull.com/product/designing-web-apis-building-
apis-that-developers-love-first-edition-jin/

Programming PHP 4th Edition Peter Macintyre

https://textbookfull.com/product/programming-php-4th-edition-
peter-macintyre/

Pro RESTful APIs: Design, Build and Integrate with


REST, JSON, XML and JAX-RS Patni

https://textbookfull.com/product/pro-restful-apis-design-build-
and-integrate-with-rest-json-xml-and-jax-rs-patni/

PHP and MySQL for Dynamic Web Sites Fifth Edition


Ullman

https://textbookfull.com/product/php-and-mysql-for-dynamic-web-
sites-fifth-edition-ullman/

Building RESTful Web Services with PHP 7 Ahmad

https://textbookfull.com/product/building-restful-web-services-
with-php-7-ahmad/
Lumen
Programming
Guide
Writing PHP Microservices, REST and
Web Service APIs

Paul Redmond
Lumen
Programming Guide
Writing PHP Microservices, REST
and Web Service APIs

Paul Redmond
Lumen Programming Guide: Writing PHP Microservices, REST and Web Service APIs
Paul Redmond
Phoenix, Arizona
USA
ISBN-13 (pbk): 978-1-4842-2186-0 ISBN-13 (electronic): 978-1-4842-2187-7
DOI 10.1007/978-1-4842-2187-7
Library of Congress Control Number: 2016953766
Copyright © 2016 by Paul Redmond
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director: Welmoed Spahr
Lead Editor: Steve Anglin
Technical Reviewer: Jacob Jensen
Editorial Board: Steve Anglin, Pramila Balan, Laura Berendson, Aaron Black, Louise Corrigan,
Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, Nikhil Karkal, James Markham,
Susan McDermott, Matthew Moodie, Natalie Pao, Gwenan Spearing
Coordinating Editor: Mark Powers
Copy Editor: Mary Behr
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Cover image designed by Freepik
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-
sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member
(owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a
Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our Special
Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales.
Any source code or other supplementary materials referenced by the author in this text are available to
readers at www.apress.com/9781484221860. For detailed information about how to locate your book’s source
code, go to www.apress.com/source-code/. Readers can also access source code at SpringerLink in the
Supplementary Material section for each chapter.
Printed on acid-free paper
To Bernadette
Contents at a Glance

About the Author ..................................................................................................... xi


About the Technical Reviewer ............................................................................... xiii
Acknowledgments ...................................................................................................xv
Introduction ...........................................................................................................xvii

■Chapter 1: Installing Lumen .................................................................................. 1


■Chapter 2: Hello Lumen ......................................................................................... 7
■Chapter 3: Creating the Book Application ........................................................... 17
■Chapter 4: Starting the Books API ....................................................................... 23
■Chapter 5: Creating, Reading, Updating, and Deleting Books .............................. 33
■Chapter 6: Responding to Errors ......................................................................... 65
■Chapter 7: Leveling Up Responses ...................................................................... 89
■Chapter 8: Validation ......................................................................................... 125
■Chapter 9: Authors ............................................................................................ 137
■Chapter 10: The /authors API Resource ............................................................ 165
■Chapter 11: Book Bundles ................................................................................. 201
■Chapter 12: Ratings ........................................................................................... 219
■Appendix: Where to Go From Here ..................................................................... 243

Index ..................................................................................................................... 245

v
Contents

About the Author ..................................................................................................... xi


About the Technical Reviewer ............................................................................... xiii
Acknowledgments ...................................................................................................xv
Introduction ...........................................................................................................xvii

■Chapter 1: Installing Lumen .................................................................................. 1


Homestead ....................................................................................................................... 1
Mac OSX ........................................................................................................................... 2
Linux ................................................................................................................................. 3
Red Hat/CentOS ...................................................................................................................................... 4
Debian/Ubuntu ........................................................................................................................................ 5

Windows ........................................................................................................................... 6
Conclusion ........................................................................................................................ 6
■Chapter 2: Hello Lumen ......................................................................................... 7
Setting Up a New Project ................................................................................................. 7
Routes .............................................................................................................................. 9
The Hello World Route .......................................................................................................................... 10
Route Parameters ................................................................................................................................. 10

Middleware and Responses ........................................................................................... 11


Global Middleware ................................................................................................................................ 11
Route Middleware................................................................................................................................. 13

vii
■ CONTENTS

The Request and Response Objects ............................................................................... 14


The Request.......................................................................................................................................... 15
The Response ....................................................................................................................................... 15

Onward ........................................................................................................................... 16
■Chapter 3: Creating the Book Application ........................................................... 17
Building Something Amazing ......................................................................................... 17
Environment Setup ......................................................................................................... 19
Checking Unit Tests ........................................................................................................ 21
Setup Complete .............................................................................................................. 22
■Chapter 4: Starting the Books API ....................................................................... 23
Creating the First Endpoint............................................................................................. 23
Setting Up Models and Seed Data .................................................................................. 26
Eloquent Books .............................................................................................................. 30
Success .......................................................................................................................... 32
■Chapter 5: Creating, Reading, Updating, and Deleting Books .............................. 33
Requesting an Individual Book ....................................................................................... 33
Creating a New Book ...................................................................................................... 41
Updating an Existing Book ............................................................................................. 49
Deleting Books ............................................................................................................... 53
Conclusion ...................................................................................................................... 63
■Chapter 6: Responding to Errors ......................................................................... 65
Test Database ................................................................................................................. 65
Model Factories .................................................................................................................................... 66
Factories in Tests .................................................................................................................................. 66

Better Error Responses .................................................................................................. 69


Framework Exception Handling ............................................................................................................ 70
JSON Exceptions .................................................................................................................................. 72

Testing the Exception Handler ........................................................................................ 74


Conclusion ...................................................................................................................... 88
viii
■ CONTENTS

■Chapter 7: Leveling Up Responses ...................................................................... 89


Introducing Fractal ......................................................................................................... 89
First Version of API Response Formatting ...................................................................... 90
The Fractal Response Class ........................................................................................... 97
The Book Transformer .......................................................................................................................... 97
The Fractal Response Class................................................................................................................ 101

Fractal Response Service ............................................................................................. 111


Integrating the Fractal Response Service .................................................................... 114
Conclusion .................................................................................................................... 124
■Chapter 8: Validation ......................................................................................... 125
First Attempt at Validation ............................................................................................ 125
More Validation Constraints ......................................................................................... 129
Custom Validation Messages ....................................................................................... 132
Other Approaches ......................................................................................................... 134
Conclusion .................................................................................................................... 135
■Chapter 9: Authors ............................................................................................ 137
The Authors Database Schema .................................................................................... 137
Fixing Broken Tests ...................................................................................................... 145
Conclusion .................................................................................................................... 163
■Chapter 10: The /authors API Resource ............................................................ 165
The GET /authors Endpoint ........................................................................................... 166
The AuthorsTransformer ..................................................................................................................... 166
The Author Controller .......................................................................................................................... 168

The GET /authors/{id} Endpoint .................................................................................... 170


A Basic Response ............................................................................................................................... 170
Including Other Models in the Response ............................................................................................ 171
The POST /authors Endpoint......................................................................................... 181
The PUT /authors/{id} Endpoint .................................................................................... 188

ix
■ CONTENTS

The DELETE /authors/{id} Endpoint .............................................................................. 197


Conclusion .................................................................................................................... 199
■Chapter 11: Book Bundles ................................................................................. 201
Defining the Relationship Between Books and Bundles .............................................. 201
The GET /bundles/{id} Endpoint .................................................................................... 206
Adding a Book to a Bundle ........................................................................................... 214
Remove a Book from a Bundle ..................................................................................... 215
Conclusion .................................................................................................................... 217
■Chapter 12: Ratings ........................................................................................... 219
Database Design .......................................................................................................... 219
Rating an Author........................................................................................................... 223
Adding an Author Rating ..................................................................................................................... 223
Deleting an Author Rating ................................................................................................................... 233

Ratings in the Author API .............................................................................................. 236


Eager Loading Ratings ................................................................................................. 240
Conclusion .................................................................................................................... 242
■Appendix: Where to Go From Here ..................................................................... 243
Laravel.......................................................................................................................... 243
Laracasts ...................................................................................................................... 243
Mockery ....................................................................................................................... 244
Guzzle ........................................................................................................................... 244

Index ..................................................................................................................... 245

x
About the Author

Paul Redmond has worked as a web developer, entrepreneur, and mentor


in software development for over a decade. He has built web applications
within startups, agencies, and enterprise customers with open-source
technologies. Paul is passionate about writing highly available applications
with PHP, JavaScript, and RESTful APIs.
Paul lives in Scottsdale, Arizona with his wife, Bernadette, three boys,
and one cat. He is usually wrangling code, kittens, and children, but finds
time to enjoy reading fantasy/fiction, writing, and watching sports.

xi
About the Technical Reviewer

Jacob Jensen is a software engineer who loves testing, automating, and


clean code; he has a passion for teaching and learning, and has deep
experience in web development, design patterns, object-oriented design,
and a multitude of programming languages and platforms.

xiii
Acknowledgments

Writing a book is challenging. Editing a book more so.


Writing a book takes patience, persistence, time, and an abundance of help from others. When I first
envisioned this title, its humble beginnings were in the form of an eBook. I conceptualized, wrote, edited,
technically edited, designed, and marketed the concepts herein.
The Laravel (https://laravel.com/) framework and the Lumen micro framework have been inspiring
in my day-to-day work. They provide a pleasant and productive development experience that rekindled
my love for PHP and inspired me to share what I’ve learned with others. Additionally, the positive feedback
and word-of-mouth about this book within the PHP and Laravel communities—specifically Taylor Otwell
(https://twitter.com/taylorotwell), Michael Dyrynda (https://dyrynda.com.au/), and Amanda Folson
(http://amandafolson.net/)—was unexpected and huge motivation to keep pressing forward and making
the book better.
My early readers provided constructive feedback, small amounts of errata and grammar issues, and
insight into what they liked about the manuscript. Early reader feedback showed that people were actually
interested in my work, and found tips and tricks that helped them.
I would like to thank Steve Anglin and Mark Powers at Apress for guiding me through the writing
process. They have made a dream of mine come true: to author a technical book. I am thankful for their help,
and the help of everyone else at Apress who assisted me throughout the process.
Within my professional circle, the direct and indirect mentoring I’ve received from my colleague
Justin Rainbow has helped shape me as a developer and I am much, much better off for it. Thank you. My
colleague Jacob Jensen, the technical editor of this book, has been invaluable for motivating me, letting me
bounce ideas off of him, and providing great feedback on a technical and peer level.
Writing a book is a big commitment, involving many late nights, and I owe my wife, Bernadette, and
my children, Hayden, Masen, and Lincoln, the biggest thanks of all. Life is short. I am so fortunate to have a
wonderful family that supports me. I love you guys!

xv
Introduction

Lumen is a framework that is designed to write APIs. With the rising popularity of microservices
(http://microservices.io/patterns/microservices.html), existing patterns like service-oriented
architecture (https://en.wikipedia.org/wiki/Service-oriented_architecture), and increased
demand for public APIs, Lumen is a perfect fit for writing the service layer in the same language as the web
applications you write.
In my experience, it’s not uncommon for PHP shops to write web applications with PHP and API
services with something like Node.js (https://nodejs.org/en/). I am not suggesting that this is a bad idea,
but I see Lumen as a chance to improve development workflows for PHP developers and for companies to
standardize around a powerful set of complimentary frameworks: Laravel and Lumen.
You can write APIs quickly with Lumen using the built-in packages provided, but Lumen can also get out
of your way and be as minimalist as you want it to be. Set aside framework benchmarks and open your mind
to increased developer productivity. Lumen is fast, but more importantly, it helps me be more productive.

The Same Tools to Write APIs and Web Applications


Lumen is a minimal framework that uses a subset of the same components from Laravel (https://laravel.com/).
Together Laravel and Lumen give developers a powerful combination of tools: a lightweight framework for
writing APIs and a full-fledged web framework for web applications. Lumen also has a subset of console
tools available from Laravel. Other powerful features from Laravel are included like database migrations,
Eloquent Models (ORM Package), job queues, scheduled jobs, and a test suite focused on testing APIs.
The development experience between Lumen and Laravel is relatively the same, which means
developers will see a productivity boost by adopting both frameworks. Together they provide a consistent
workflow and can simplify the software stack for developers, release engineers, and operations teams.

Who This Book Is For


This book is for programmers that want to write APIs in PHP. Familiarity with the HTTP spec, Composer,
PHPUnit, and the command line will help, but this book walks you through each step of building an API.
You don’t need to be an expert on these subjects, and more experienced developers can skip things they
understand to focus on the specific code needed to write APIs in Lumen. This book does not cover every
detail of using Lumen, but focuses on the most important concepts needed to write testable APIs with Lumen.

Conventions Used in This Book


The book is a hands-on guide to building a working API, so you will see tons of code samples throughout the
book. I will point out a few conventions used so that you can understand the console commands and code.
The code is meant to provide a fully working API; you can follow along or copy and paste code samples.

xvii
■ INTRODUCTION

Code Examples
A typical PHP code snippet looks like this:

Example PHP Code Snippet


/**
* A Hello World Example
*/
$app->get('/', function () {
return 'Hello World';
});

To guide readers, approximate line numbers are used when you will be adding a block of code to an
existing class or test file:

Example PHP Code Snippet


10 /**
11 * A Foobar Example
12 */
13 $app->get('/foo', function () {
14 return 'bar';
15 });

Longer lines end in a backslash (\) and continue to the next line:

Example of Long Line in PHP


$thisIsALongLine = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qu\
os unde deserunt eos?'

When you need to run console commands to execute the test suite or create files, the snippet appears as
plain text without line numbers. Lines start with $, which represents the terminal prompt.

Example Console Command


$ touch the/file.php

Console commands that should be executed in the recommended Homestead1 environment will be
indicated like the following example. The book removes extra output from PHPUnit tests to make examples
less verbose.

Console Command in the Homestead Virtual Machine


# vagrant@homestead:~/Code/bookr$
$ phpunit

OK (1 test, 4 assertions)

1
https://laravel.com/docs/homestead

xviii
■ INTRODUCTION

Code Errata and Feedback


Submit errata to lumenapibook@gmail.com, or via the book’s apress.com product page, located at
www.apress.com/9781484221860. Feel free to send in typos, inaccurate descriptions, code issues, praise,
feedback, and code suggestions on better ways of doing something. Please don’t be shy; these things make
my book better!

Tips, Notes, and Warnings

YOUR ASIDE TITLE

This is an aside

Hey, Listen! Tips give you pointers related to concepts in the book.

Danger! Warnings point out potential issues and security concerns.

Need the Info This aside provides additional info related to code and concepts.

Git Commit: Amazing Refactor! rm3dwe2f

This is an example of a code commit if you are following along and using git to commit your work.

Discussions This tip includes deeper discussions around topics in the book. Advanced users can
generally skip these.

Tools You Will Need


All tools are recommended, but if you know what you’re doing, you can set up your own coding environment
and skip the recommended tools. You might even have these tools already; just make sure they are relatively
up-to-date. All tools listed are free unless otherwise noted.

VirtualBox
This book uses a virtual machine to run the API application. You will need to download VirtualBox if you
plan on using the recommended Homestead environment. VirtualBox works on Windows, Mac, and Linux
(www.virtualbox.org).

xix
■ INTRODUCTION

Vagrant
Homestead also requires Vagrant (www.vagrantup.com/) to manage and provision virtual machines. Vagrant
works on Windows, Mac, and Linux (Debian and CentOS).

Version Control
If you want to work along in the book and commit your code as you go (recommended), you need to install a
version control system. I recommend git, but anything you want will do.

Editor/IDE
Most readers will already have a go-to editor. I highly recommend PhpStorm (www.jetbrains.com/phpstorm/),
which is not free, but it pays for itself. Other common IDE options are Eclipse PDT and NetBeans.
If you don’t like IDEs, I recommend Sublime Text (www.sublimetext.com/) or Atom (https://atom.io/).
If you are on Mac, TextMate (https://macromates.com/) is another great choice. TextMate 2 is marked as
“beta” but is reliable.

xx
CHAPTER 1

Installing Lumen

Before you start diving into Lumen, you need to make sure PHP is installed. You’ll also need a few other tools
to develop a real application. You can get PHP a number of ways, but here is my recommendation for all
platforms: Laravel Homestead (laravel.com/docs/homestead). I also include a few different ways to install
PHP locally if you are interested, but the book examples will use Homestead. I highly encourage using
Homestead to work through this book.
To work through the applications in this book, you will need
• PHP >= 5.5.9, as well as a few PHP extensions
• Composer
• MySQL Database
Homestead comes with a modern version of PHP called Composer (https://getcomposer.org/), and
a few database options, so you don’t need to worry about the requirements if you are using Homestead; if
you are not using Homestead, you will need >= PHP 5.5.9 as outlined by the Lumen installation instructions
(https://lumen.laravel.com/docs/5.2/installation#installation).
The last thing on the list is a database. Lumen can be configured to use different databases including
MySQL, SQLite, PostgreSQL, or SQL Server. We will use MySQL (any MySQL variant will do) for this book.
MySQL is the default database connection in the Lumen Framework database configuration (https://github.
com/laravel/lumen-framework/blob/5.2/config/database.php) so we will stick with the convention.

Homestead
Laravel Homestead is the best development environment choice because it provides a complete
development environment for all your Laravel and Lumen projects. Homestead provides some solid benefits
for your development environment as well, including the following:
• Isolated environment on a virtual machine
• Works on Windows, Mac, and Linux
• Easily configure all your projects in one place
As mentioned in the introduction, Homestead requires Vagrant (www.vagrantup.com/) and VirtualBox
(www.virtualbox.org/) so you will need to install both. Follow the installation instructions
(https://lumen.laravel.com/docs/5.2/installation#installation) to finish setting up Homestead.

Electronic supplementary material The online version of this chapter (doi:10.1007/978-1-4842-2187-7_1)


contains supplementary material, which is available to authorized users.

© Paul Redmond 2016 1


P. Redmond, Lumen Programming Guide, DOI 10.1007/978-1-4842-2187-7_1
CHAPTER 1 ■ INSTALLING LUMEN

Once you complete the installation instructions you should be able to run the vagrant ssh command
within the Homestead project and successfully ssh into your Homestead virtual machine. You will revisit
Homestead to set up your sample application in Chapter 2, and then you will set up another application in
Chapter 3 that you will work on throughout the remainder of the book.
When the install instructions instruct you to clone the Homestead git repository, I encourage you
to clone it to ~/Code/Homestead to follow along with the book, or you can adapt the examples to match
whatever you pick (see Listing 1-1).

Listing 1-1. Cloning the Homestead Project to ~/Code/Homestead


$ mkdir -p ~/Code
$ git clone https://github.com/laravel/homestead.git Homestead

Once you finish the Homestead installation instructions you should be able to ssh into the virtual
machine (Listing 1-2).

Listing 1-2. SSH Into Homestead


$ cd ~/Code/Homestead
$ vagrant ssh
Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.19.0-25-generic x86_64)

* Documentation: https://help.ubuntu.com/
Last login: Tue Feb 2 04:48:52 2016 from 10.0.2.2
vagrant@homestead:~$

You can type “exit” or press Control+D to exit the virtual machine. The homestead repository will be
at ~/Code/Homestead and this is the path you will use in this book for your applications. I encourage you
to review the Homestead.yaml file at ~/.homestead/Homestead.yaml after you finish installing Homestead.
Once you get Homestead installed, you can skip ahead to Chapter 2. See you in the next section!

■ Optional Local Instructions The following sections offer information if you are interested in running PHP
locally, so feel free to skip them. I cannot guarantee these instructions, but for the most part they should work
for you.

Mac OSX
If you want to develop locally on OS X, I recommend using Homebrew (http://brew.sh/) to install PHP
and MySQL. The PHP installation that ships with OS X will probably suffice, but I will show you how to
install PHP with Homebrew instead of dealing with the different versions of PHP that ship with different
versions of OS X.
To install packages with Homebrew, you will need Xcode developer tools and the Xcode command line
tools. XCode is a rather large download—I’ll be waiting for you right here.
Once you have Xcode, follow the installation instructions (http://brew.sh/#install) on Homebrew’s
site. Next, you need to tell brew about “homebrew-php” so you can install PHP 5.6 (Listing 1-3).

2
CHAPTER 1 ■ INSTALLING LUMEN

Listing 1-3. Tap homebrew-php


$ brew tap homebrew/dupes
$ brew tap homebrew/versions
$ brew tap homebrew/homebrew-php
$ brew install php56 php56-xdebug

Once the installation finishes, verify that you have the right version of PHP in your path (Listing 1-4).

Listing 1-4. Verifying PHP


$ php --version
PHP 5.6.16 (cli) (built: Dec 7 2015 10:06:24)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

Next, you need to install the MySQL database server with Homebrew (Listing 1-5).

Listing 1-5. Installing MySQL with Homebrew


$ brew install mysql

Once the MySQL installation is finished, make sure you can connect to the database server (Listing 1-6).

Listing 1-6. Connecting to MySQL


$ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3795
Server version: 5.6.26 Homebrew
...
mysql>

I highly recommend updating the root password (http://dev.mysql.com/doc/refman/5.6/en/


resetting-permissions.html) and adding another user besides root, which you will use to connect to
MySQL. Although the database is local, securing MySQL is a good habit.
You can configure Apache or Nginx locally if you want to use a web server (Mac ships with Apache).
I’ll leave the rest up to you, but it should be pretty easy to get PHP and a web server going on a Mac by
searching Google.

Linux
Here are simple instructions to install PHP on Unix-like systems; this section includes the most popular
distributions like CentOS and Ubuntu. This is not an exhaustive set of setup instructions but it should be
enough to work with Lumen.

3
CHAPTER 1 ■ INSTALLING LUMEN

Red Hat/CentOS
To install a modern version of PHP on Red Hat and CentOS, I recommend using the Webtatic (https://
webtatic.com/) yum repository. First, add the repository with the Webtatic release RPM; you should use the
repository that matches your specific version (Listing 1-7).

Listing 1-7. Adding the Webtatic Repository


# CentOS/REHL 7
$ yum -y update
$ rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
$ rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

# CentOS/REHL 6
$ yum -y update
$ rpm -Uvh https://mirror.webtatic.com/yum/el6/latest.rpm

Next, install the following PHP packages and verify that PHP was installed properly (Listing 1-8).

Listing 1-8. Installing PHP Packages from Webtatic


$ yum install \
php56w.x86_64 \
php56w-mysql.x86_64 \
php56w-mbstring.x86_64 \
php56w-xml.x86_64 \
php56w-pecl-xdebug.x86_64

# Verify
$ php --version
PHP 5.6.16 (cli) (built: Nov 27 2015 21:46:01)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

Next, install the MySQL client and server (Listing 1-9).

Listing 1-9. Installing MySQL on REHL


$ yum install mysql-server mysql

Once MySQL is installed, you should set a root password (Listing 1-10).

Listing 1-10. Securing the MySQL Installation


$ /usr/bin/mysql_secure_installation

Follow the prompts and you should be all set!

4
CHAPTER 1 ■ INSTALLING LUMEN

Debian/Ubuntu
On Debian systems I recommend using the php5-5.6 PPA (https://launchpad.net/~ondrej/+archive/
ubuntu/php5-5.6) from Ondrej Surý (https://launchpad.net/~ondrej) or the PHP 7 version of the same
PPA. Installation of the PPA varies slightly between different versions. Most of the steps will remain the same,
but the following are the steps for Ubuntu 14.04 and Ubuntu 12.04.
First, install a couple dependencies needed to add the PPA. If you are using Ubuntu 14.04, see Listing 1-11.

Listing 1-11. Installing Dependencies Needed and the PPA on Ubuntu 14.04
$ apt-get install -y language-pack-en-base
$ apt-get install -y software-properties-common --no-install-recommends
$ LC_ALL=en_US.UTF-8 add-apt-repository ppa:ondrej/php5-5.6

If you are using Ubuntu 12.04, run the code in Listing 1-12 instead.

Listing 1-12. Installing Dependencies and the PPA on Ubuntu 12.04


$ apt-get install -y language-pack-en-base
$ apt-get install -y python-software-properties --no-install-recommends
$ LC_ALL=en_US.UTF-8 add-apt-repository ppa:ondrej/php5-5.6

Note that non-UTF-8 locales will not work (https://github.com/oerdnj/deb.sury.org/issues/56)


at the time of writing. Next, update and install the required packages and verify; the commands are the same
for Ubuntu 14.04 and 12.04 (Listing 1-13).

Listing 1-13. Updating and Installing Packages


$ apt-get update
$ apt-get install -y \
php5 \
php5-mysql \
php5-xdebug

# Verify
$ php --version
PHP 5.6.16-2+deb.sury.org~precise+1 (cli)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies

Next, install MySQL server and client packages, make the MySQL service start on boot, and start the
service manually (Listing 1-14).

Listing 1-14. Installing MySQL Packages on Ubuntu


$ apt-get install \
mysql-server \
mysql-client
$ sudo update-rc.d mysql defaults
$ sudo service mysql start

5
CHAPTER 1 ■ INSTALLING LUMEN

During the installation of the mysql-server package you should be prompted to update the root
password, which will look similar to Figure 1-1.

Figure 1-1. Configuring MySQL Root Password

Verify that you can connect to MySQL after you finish installing MySQL and setting a root password
(Listing 1-15).

Listing 1-15. Connecting to MySQL


$ mysql -u root -p
Enter password:

mysql>

At this point, you should have everything required to get through this book using the built-in PHP server
on a local Ubuntu machine.

Windows
I recommend using Homestead (http://laravel.com/docs/5.1/homestead#installation-and-setup) to
work through this book on Windows.

Conclusion
You should now have a working environment that you can use to write Lumen applications! Let’s summarize
what we did in this chapter:
• Installed Vagrant and VirtualBox
• Installed the Homestead virtual machine
• Covered alternative ways of installing PHP and MySQL
I want to emphasize how easy Homestead makes getting a solid, portable development environment
working with little effort. Now that you have PHP installed, it’s time to learn Lumen!

6
CHAPTER 2

Hello Lumen

Let’s dive right into Lumen. In this chapter, you’ll learn how to set up a new Lumen project and you’ll explore
some of Lumen’s basic features:
• Routing
• Middleware
• Requests
• Responses
To follow along, you should have the recommended Homestead environment from Chapter 1 installed.

Setting Up a New Project


Before you can get started, you need to create a new Lumen project in Homestead. To create a new project,
ssh into Homestead virtual machine and use Composer to create a new Lumen project (Listing 2-1).

Listing 2-1. Creating a New Lumen Application in Homestead


# On your local machine
$ cd ~/Code/Homestead
$ vagrant ssh

# In the virtual machine


vagrant@homestead:~$ cd ~/Code
vagrant@homestead:~/Code$ composer create-project \
laravel/lumen=~5.2.0 --prefer-dist hello-lumen
vagrant@homestead:~/Code$ cd hello-lumen

The book examples assume Homestead was cloned to the suggested path ~/Code/Homestead. Adjust the
commands if you cloned Homestead elsewhere.

In the Homestead virtual machine, you change the directory to ~/Code, where your application files will
live. Next, you use Composer’s create-project command to create a new Lumen project. The last argument
in the create-project command tells Composer to create the project in the path ~/Code/hello-lumen. Now
that you’ve created a new project on the virtual machine, you should also see a shared local path at ~/Code/
hello-lumen on your own machine.

© Paul Redmond 2016 7


P. Redmond, Lumen Programming Guide, DOI 10.1007/978-1-4842-2187-7_2
CHAPTER 2 ■ HELLO LUMEN

The next step is telling Homestead about the hello-lumen application. On your local machine, open
~/.homestead/Homestead.yaml and find the default project under the sites key (Listing 2-2).

Listing 2-2. Default Sites Configuration in Homestead.yaml


sites:
- map: homestead.app
to: /home/vagrant/Code/Laravel/public

Replace it with the code in Listing 2-3 and save the file.

Listing 2-3. Default Sites Configuration in Homestead.yaml


sites:
- map: hello-lumen.app
to: /home/vagrant/Code/hello-lumen/public

Configure the project’s hostname and the path to the public folder on the virtual machine. Save the
file and run vagrant provision on your local machine to update Homestead with the new configuration
changes (Listing 2-4).

Listing 2-4. Provision Vagrant Locally


> cd ~/Code/Homestead
> vagrant provision

Every time you update Homestead.yaml you will need to run the vagrant provision command.

Once Vagrant is finished provisioning the machine, the last step is adding an entry to the hosts file on
your local machine. The hosts file will map the hostname hello-lumen.app to your virtual machine’s IP
address. You can find Homestead’s IP address by finding the ip key in the ~/.homestead/Homestead.yaml
file—you should see something like ip: "192.168.10.10".
Take note of the IP address so you can add it to the local hosts file. To update the hosts file on Mac or
Linux, the file path is /etc/hosts; if you are on Windows, the file path is C:\Windows\System32\drivers\
etc\hosts. Add the line from Listing 2-5 to your hosts file.

Listing 2-5. Adding Hostname to Hosts File


192.168.10.10 hello-lumen.app

Be sure to use the IP address found in your ~/.homestead/Homestead.yaml file, not the IP shown in this book.
It might be the same, but make sure.

After updating the hosts file, visit http://hello-lumen.app/ in your browser and you should see
something similar to Figure 2-1.

8
CHAPTER 2 ■ HELLO LUMEN

Figure 2-1. Lumen default route

You should now have a working hello-lumen project. Let’s get to work!

Routes
Routing (https://lumen.laravel.com/docs/5.2/routing) is the first feature we will cover. Application
routes in Lumen are defined in the app/Http/routes.php file. In the most basic form, routing configuration
includes an HTTP verb (GET, POST, etc.) which accepts a URI and a Closure. We will use the Closure style
routes in this chapter, but we will use controllers throughout the book.
The first routes will be two simple “Hello World” examples to introduce you to routing:
• /hello/world which responds with the text “Hello World”
• /hello/{name} which responds with a customized greeting
Before you define your own routes, if you open the file app/Http/routes.php, the default contents
looks like Listing 2-6.

Listing 2-6. The Default Lumen Route in app/Http/routes.php


<?php

$app->get('/', function () use ($app) {


return $app->version();
});

The $app variable in the routes file is an instance of \Laravel\Lumen\Application which is defined
in the bootstrap/app.php file. The application routes file is imported near the end of bootstrap/app.php
(Listing 2-7).

Listing 2-7. The Bootstrap File Importing Routes


$app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
require __DIR__.'/../app/Http/routes.php';
});

9
CHAPTER 2 ■ HELLO LUMEN

The Hello World Route


Your first route is a simple /hello/world route that responds with the text “Hello World”. Open up the app/
Http/routes.php file and add the route shown in Listing 2-8.

Listing 2-8. The /hello/world Route in app/Http/routes.php


18 $app->get('/hello/world', function () use ($app) {
19 return "Hello world!";
20 });

The $app->get() method accepts a URI and a \Closure that gets executed to create the response. The
route returns a string response. If you visit http://hello-lumen.app/hello/world in your browser, you will
see the response “Hello world!”
The $app instance has HTTP methods like get, put, post, and delete which are used to define routes.
In this example, the defined route will respond to GET requests. If you try to send a POST request, you will get
a 405 response (Listing 2-9).

Listing 2-9. Trying to POST to the Hello World Route


$ curl -I -XPOST http://hello-lumen.app/hello/world
HTTP/1.1 405 Method Not Allowed
Server: nginx/1.9.7
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
allow: GET
Cache-Control: no-cache, private
date: Tue, 29 Dec 2015 06:28:46 GMT

Route Parameters
The second route you are going to add has a dynamic route parameter (Listing 2-10).

Listing 2-10. Your Second Route


22 $app->get('/hello/{name}', function ($name) use ($app) {
23 return "Hello {$name}";
24 });

The route URI has a required route parameter {name} which is then passed to the \Closure. You then
return your concatenated $name variable, which creates the HTTP response shown in Listing 2-11.

Listing 2-11. Example Response from the Router


$ curl -i http://hello-lumen.app/hello/paul
HTTP/1.1 200 OK
Server: nginx/1.9.7
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive

10
CHAPTER 2 ■ HELLO LUMEN

Cache-Control: no-cache
Date: Sat, 26 Dec 2015 21:27:19 GMT

Hello paul

You can define multiple route parameters in one route and add constraints to them (only digits). I will
go over plenty of route examples as you work through this book.

Middleware and Responses


Similar to express.js (http://expressjs.com/) and many other web frameworks, Lumen has HTTP
middleware (https://lumen.laravel.com/docs/5.2/middleware). Middleware provides a way to filter
incoming HTTP requests before a defined route handles the request. You can use middleware to do any
number of things, like authentication, validating a signed request, and CORS support, to name a few.
Middleware classes are typically created in the app/Http/Middleware path by convention; I suggest sticking
to the convention unless you plan on writing a standalone package that includes middleware.
Lumen has two types of middleware configuration: global middleware and route middleware. What is the
difference between the two types? Global middleware runs on every HTTP request and route middleware runs
on specific routes (or groups of routes) configured to run the middleware. We will go over an example of each.
We will also cover an example of creating a response object in middleware. We will work with response
objects throughout this book, but we will only touch on them lightly in this chapter.

Global Middleware
The first middleware example you will write is a simple request logger that logs every incoming request
to the storage/logs/lumen.log application log file. Configuring the logging middleware to be a global
middleware makes sense because we want to log all HTTP requests.
Start by creating the file app/Http/Middleware/RequestLogMiddleware.php with the contents shown in
Listing 2-12.

Listing 2-12. Creating the RequestLogMiddleware


1 <?php
2
3 namespace App\Http\Middleware;
4
5 use Log;
6 use Closure;
7 use Illuminate\Http\Request;
8
9 class RequestLogMiddleware
10 {
11 public function handle(Request $request, Closure $next)
12 {
13 Log::info("Request Logged\n" .
14 sprintf("~~~~\n%s~~~~", (string) $request));
15
16 return $next($request);
17 }
18 }

11
CHAPTER 2 ■ HELLO LUMEN

Middleware needs to define a handle method that accepts two parameters: the request object and a
Closure instance. The request object is an instance of Illuminate\Http\Request and represents the current
request.

Each middleware must call return $next($request) at some point in order to continue processing the request.

Now you need to register your new middleware in bootstrap/app.php (Listing 2-13).

Listing 2-13. Registering a Global Middleware


62 // $app->middleware([
63 // App\Http\Middleware\ExampleMiddleware::class
64 // ]);
65
66 $app->middleware([
67 App\Http\Middleware\RequestLogMiddleware::class
68 ]);

The Application::middleware() method accepts an array of middleware class names. I have included
the commented out middleware so you can see other types of middleware that ship with Lumen.
There is one more step to get the middleware working: you need to enable facades (https://laravel.
com/docs/5.2/facades) so the Log class will work as expected.
In bootstrap/app.php, uncomment the code in Listing 2-14.

Listing 2-14. Enabling Facades in the Application


26 // $app->withFacades();
27 $app->withFacades();

With facades enabled, the new middleware will add a log entry to storage/logs/lumen.log for every
request (Listing 2-15).

Listing 2-15. Partial Log Output from RequestLogMiddleware in lumen.log


[2015-12-26 21:47:53] lumen.INFO: Request Logged
GET /hello/paul HTTP/1.1
...

■ Facades The facade pattern provides a static interface to classes available in the service container
(https://lumen.laravel.com/docs/5.2/container).

It offers a clean style that I personally like, but you are not required to use it.

Lumen offers various ways of resolving dependencies out of the container, which you will see in this book.
Also be sure to read the “Resolving” section of the documentation (https://lumen.laravel.com/docs/5.2/
container).

12
CHAPTER 2 ■ HELLO LUMEN

The middleware should be working. What happens if we forget to call $next($request)? To experiment,
you would get the following response (Listing 2-16) by removing return $next($request) from the
middleware (be sure to put it back).

Listing 2-16. What Happens When $next($request) Is Not Returned?


$ curl -i http://hello-lumen.app/hello/paul
HTTP/1.1 200 OK
Server: nginx/1.9.7
Date: Sat, 26 Dec 2015 21:54:00 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive

Middleware can also control whether or not the HTTP request should continue being processed. For
example, an authentication middleware would deny access to guests trying to access secured parts of the
application by sending a 403 Forbidden response instead of proceeding with the request. Middleware
should either allow the request to continue or send a response back.

Route Middleware
Our next middleware will be route middleware for the /hello/{name} route. Create a new middleware class
in app/Http/Middleware/HelloMiddleware.php with the code from Listing 2-17.

Listing 2-17. Creating the HelloMiddleware


1 <?php
2
3 namespace App\Http\Middleware;
4
5 use Closure;
6 use Illuminate\Http\Request;
7
8 class HelloMiddleware
9 {
10 public function handle(Request $request, Closure $next)
11 {
12 if (preg_match('/balrog$/i', $request->getRequestUri())) {
13 return response('YOU SHALL NOT PASS!', 403);
14 }
15
16 return $next($request);
17 }
18 }

The HelloMiddleware checks the request URI against a case-insensitive regex pattern. If the URI
matches the regex pattern, the middleware returns a 403 forbidden response error with the response()
helper function. If the user is not asking to say hello to a balrog, the request will proceed as expected.

13
Another Random Document on
Scribd Without Any Related Topics
uninterruptedly into the tube by means of a small ventilator. This
sweeps away, as it were, the vapours of calomel, and in a straight
tube will carry them a distance of 60 feet, to avoid which the end of
the recipient is immersed in water, by which means the calomel is
moistened and falls down. This plan, slightly modified, is now
extensively adopted in this country.
8. (Precipitated calomel; Calomelas præcipitatum, L.) Digest pure
quicksilver, 9 parts, in nitric acid (sp. gr. 1·02 to 1·25), 8 parts, until
no more metal will dissolve, applying heat as the effervescence
ceases; then mix the hot liquid quickly with a boiling solution of
sodium chloride, 8 parts, dissolved in water (slightly acidulated with
hydrochloric acid), 64 parts; lastly, well wash the precipitate in
boiling distilled water, and dry it. The product, when the process is
skilfully managed, is perfectly white and pure.
Prop. A heavy, white, tasteless powder; insoluble in water,
alcohol, and cold dilute nitric acid; volatilises at a temperature below
redness, and yields a white or yellowish-white sublimate; hot nitric
acid oxidises and dissolves it; alkalies, the alkaline carbonates, and
lime water, decompose it, with the production of the black oxide;
ammonia converts it into a dark slate-grey coloured powder (BLACK
PRECIPITATE—Kane). Sp. gr. 7·14 (Boullay; 7·156—Pelouze and
Fremy; 7·176—Ure).
Pur. Calomel is frequently contaminated with small quantities of
corrosive sublimate, which may be detected by digesting a little in
alcohol, decanting the clear portion, and testing it with a drop or two
of potassium hydrate, when a reddish precipitate will be formed if
any mercuric chloride be present. It is pulverulent, whitish, and
sublimes entirely by heat. It becomes black on the addition of
potassium hydrate, then, heat being applied, it runs into globules of
mercury. Neither silver nitrate, lime water, nor sulphuretted
hydrogen, being added to the water in which it has been washed, or
boiled throws down anything.
Uses. Calomel is one of the milder mercurials, and in this
respect takes its position immediately after blue pill, mercury with
chalk, and the grey oxide; but it probably ranks before all the other
salts of mercury. Universal experience appears to show it to be a
most valuable alterative when judiciously administered. With this
intention it is given in doses of 1⁄ 4 to 1 gr., generally combined with
antimonials, as in Plummer’s pill, and repeated every night, or every
other night, for some time, followed by a mild saline aperient in the
morning. As a purgative, 2 to 5 gr., either combined with or followed
by other purgatives, as jalap, rhubarb, senna, colocynth, Epsom
salts, &c. As a vermifuge, 2 to 5 gr., over-night, followed by a
sufficient dose of castor oil next morning. Combined with opium it is
frequently used in various complaints to produce salivation, or bring
the system under the influence of mercury. It is also employed as a
sedative and errhine, and in a vast number of other indications. It is,
indeed, more frequently used, and in a greater variety of complaints,
than probably any other medicine.
Obs. Of the two methods of preparing calomel, that by
precipitation is not only the best, but the most economical. That by
sublimation is, however, the one generally adopted in England. Mr
Brande states that “a small portion of sodium chloride is apt to
remain combined with it, which might affect its medical uses.” Such
a contamination is not found in carefully prepared precipitated
calomel, although we doubt whether the quantity of it which exists
in any of the samples we have met with (being merely a trace)
would at all interfere with its therapeutical action; more especially
when it is recollected that alkaline chlorides are present in, not
merely the primæ viæ, but also in every part of the animal body.
The late Mr Fownes, a chemist who was unsurpassed in the accuracy
of his researches, and the caution and delicacy with which he
expressed his opinions, once assured us that calomel was more
easily and cheaply prepared of the best quality by precipitation than
by sublimation, and that if, from careless manipulation, it
occasionally contained a minute quantity of common salt, this was of
much less importance than the contamination of corrosive sublimate,
which was frequently present in samples of sublimed calomel.
To produce a superior article of calomel in the dry way is a
somewhat difficult task, and the process frequently fails in the hands
of inexperienced operators. The solution of the mercury is best made
in an iron vessel, and the sublimation should be conducted
(preferably) in an earthenware retort with a short but very wide
neck, and fitted in a spacious receiver, having a large flat bottom,
also of earthenware, and containing a little cold water. On the small
scale the heat may be applied by means of a sand bath. The form
above given for calomel, by precipitation, produces a large product,
perfectly free from corrosive sublimate and mercurous nitrate, and is
consequently free from the objections frequently raised against that
mode of preparing it.
“The form in which calomel sublimes depends much upon the
dimensions and temperature of the subliming vessels. In small
vessels it generally condenses in a crystalline cake, the interior
surface of which is often covered with beautiful quadrangular
prismatic crystals, transparent, and of a texture somewhat elastic or
horny. In this state it acquires, by the necessary rubbing into
powder, a decided yellow or buff colour, more or less deep,
according to the degree of trituration it has undergone. If, on the
contrary, the calomel be sublimed into a very capacious and cold
receiver, it falls in an impalpable and perfectly white powder, which
requires only one elutriation to fit it for use; it then remains perfectly
colourless.” (Brande.)
The long-continued action of steam on calomel in a state of
minute division is attended by the formation of a small quantity of
corrosive sublimate. (Righini.) Boiling water, hot air, and light, also
produce a like effect.
Mercurous Iodide. HgI. Syn. Subiodide Of mercury, Green iodide
of mercury, Mercurous iodide; Hydrargyri iodidum viride (B. P.),
Hydrargyri subiodum, H. iodidum (Ph. L.), H. i. viride (Ph. D.), L. Prep.
1. (B. P.) Mercury, 1 oz.; iodine, 278 gr.; rectified spirit, a sufficiency.
Rub the iodine and mercury in a porcelain mortar, moistening
occasionally with a few drops of spirit, and continue the trituration
until the mass assumes a uniform green colour, and no metallic
globules are visible.
2. Precipitate a solution of mercurous nitrate by another of
mercurous potassium iodide; wash the precipitate, first in a solution
of sodium chloride, and then in pure water; lastly, dry it in the
shade.
3. (Ph. L.) Mercury, 1 oz.; iodine, 5 dr.; triturate together,
gradually adding of rectified spirit, q. s. (about 1 to 2 fl. dr.), until
globules are no longer seen; dry the powder, by a gentle heat, in the
shade, as quickly as possible, and preserve it in a well-stoppered
black glass vessel. The formula of the Ph. D. is similar.
Prop., &c. A heavy, greenish-yellow powder; insoluble in water,
alcohol, and a solution of common salt; soluble in ether, and slightly
so in an aqueous solution of iodide of potassium. “Freshly prepared,
it is yellowish. Heat being cautiously applied, it sublimes in red
crystals, which quickly turn yellow, and, on access of light, blacken.
It is insoluble in a solution of chloride of sodium.” The process of the
Ph. L. and F. P. does not answer when larger quantities than 4 or 5
oz. are prepared at once, owing to the great heat generated by the
reaction of the ingredients, and the consequent volatilisation of a
portion of the iodine, by which the colour of the product suffers.—
Dose, 1⁄ 8 to 1 gr., made into pills; “in syphilis and scrofula,
especially where they occur in the same individual.” It is also used
externally, in the form of ointment. It is very poisonous.
Mercurous Nitrate. HgNO 3. Syn. Subnitrate of mercury;
Hydrargyri subnitras, H. nitras, H. protonitras, L. Prep. 1. (Neutral.) By
digesting mercury in excess of cold dilute nitric acid, observing to
remove the short prismatic crystals within a short time after they are
formed; these, when drained, and redissolved in water slightly
acidulated with nitric acid, furnish crystals of pure neutral mercurous
nitrate by cautious evaporation.
2. (Basic.) Deposited after some time, when excess of mercury
has been employed as above. A fine crystallised salt.
Prop., &c. Both the above are decomposed by water, but the
former may be dissolved in a very small quantity without
decomposition. When the neutral salt is triturated with an excess of
sodium chloride, and water subsequently added, the whole of the
mercury is thrown down as calomel, and the filtered supernatant
liquid does not contain corrosive sublimate. If this salt is detected,
the salt examined contained mercuric nitrate, and if any basic
mercurous nitrate was present, the newly formed calomel has a grey
or black colour, due to presence of oxide.—Dose. Of the neutral
salts, 1⁄ 16 to 1⁄ 8 gr. It is seldom used internally. A solution is
sometimes employed as a mild caustic to ulcers; and, more dilute, as
a lotion in lepra, porrigo, psoriasis, etc.; or made into an ointment,
in the same diseases.
Mercurous Oxide. Hg 2O. Syn. Suboxide of Mercury, Grey o. of
m., Black o. of m., Mercurous o., Dioxide of m., Protoxide of M. † ;
Hydrargyri Suboxydum, H. oxydum, H. o. cinereum, H. o. nigrum, L. Prep.
1. (Ph. L. 1836.) Calomel, 1 oz.; lime water, 1 gall.; mix, agitate well
together, decant the clear liquid after subsidence, and well wash the
sediment with distilled water; lastly, drain and dry it, wrapped in
bibulous paper, in the air.
2. (Ph. D. 1826.) Sublimed calomel, 1 part; solution of
potassium hydrate (warm), 4 parts; triturate together, &c., as last.
3. Briskly triturate calomel in a mortar with pure potassium
hydrate, in excess; wash it with water, and dry it in the shade.
Prop., &c. A very dark grey or black powder, suffering
decomposition by exposure to light and air, becoming olive coloured,
from a portion being resolved into metallic mercury and binoxide.
Digested for a short time in dilute hydrochloric acid, it remains
undissolved, and the filtered liquid is not affected by potassium
hydrate, or by ammonium oxalate. It is totally soluble in acetic acid,
and entirely dissipated by heat. As a medicine pure mercurous oxide
is one of the mildest of the mercurials, and is used both internally
and externally; but chiefly as a fumigant, or made into an ointment.
—Dose, 1⁄ 2 gr. to 3 gr. twice a day.
Mercurous Phosphate, Syn. Hydrargyri phosphas, L. Prep. Add
a solution of mercurous nitrate (slightly acidulated with nitric acid) to
a solution of sodium phosphate, and wash and dry the precipitate
which forms. In its physical characters it closely resembles calomel,
than which it is said to be more appropriate in certain cases,
especially in secondary syphilis. Alkalies turn it black.—Dose, 1⁄ 4 to
1 gr., made into a pill with sugar and aromatics.
Mercurous Sulphate. Hg 2SO 4. Syn. Subsulphate of mercury,
Sulphate of the suboxide of m., Protosulphate of m. † ; Hydrargyri
subsulphas, L. Prep. By adding sulphuric acid to a solution of
mercurous nitrate. The salt falls as a white crystalline powder.
Mercurous Sulphide. Hg 2S. Syn. Subsulphate of mercury;
Hydrargyri subsulphuretum cum sulphure, H. s. nigrum, L. Prep. 1. (Pure.)
This falls as a black precipitate when a solution of mercurous nitrate
is treated with sulphuretted hydrogen or ammonium sulphide.
2. (Impure; Ethiops mineral; Hydrargyri sulphuretum cum sulphure,
H. s. nigrum—Ph. L. 1824 & Ph. D. 1826); (Æthiops mineralis—Ph. L.
1836 & Ph. D. 1826.) (Quicksilver and sulphur, equal parts, triturated
together in a stoneware mortar—Ph. D.) until globules are no longer
visible.
Prop., &c. The last preparation of mercurous sulphide is alone
employed medicinally. It is a heavy, insoluble, black powder. It is
frequently met with imperfectly prepared, and sometimes
adulterated. It is said to be a mixture of mercurous sulphide and
sulphur, in variable proportions depending on the length of the
trituration. On the large scale it is generally made by melting the
ingredients together, and afterwards reducing the mass to a fine
powder in a mill or mortar. It is said to be vermifuge and alterative,
and has been used in some cutaneous and glandular diseases, but
appears to be nearly inert.—Dose, 5 to 30 gr.
Mercurous Tartrate. (P. Cod.) Syn. Proto-tartrate of mercury,
Hydrargyri tartras. Made by adding a solution of proto-nitrate of
mercury in water, slightly acidulated with nitric acid, to a solution of
tartrate of potash as long as a precipitate forms. Wash it with
distilled water, dry it in the shade, and keep it in bottles covered with
black paper.—Dose, 1 to 2 gr.
MERCURY, Other Preparations of.
Mercury, Hahnemann’s. Syn. Hahnemann’s soluble mercury, H.’s
black oxide of m., Black precipitate of m.; Hydrargyri præcipitatum nigrum,
Mercurius solubilis Hahnemanni, L.—a. By dropping weak ammonia into
a solution of mercurous nitrate as long as the precipitate formed is
of a black colour; the powder is washed, dried in the shade without
artificial heat, and then preserved from the light and air.
(Ph. Bor. 1847.) Solution of mercurous nitrate (recent; sp. gr.
1·1), 9 1⁄ 4 oz.; distilled water, 2 lbs.; mix, filter, and add to the
solution of ammonia (sp. gr. ·960), 1⁄ 2 oz., diluted with water, 4 fl.
oz.; collect the powder immediately on a filter, wash it with water, 3
fl. oz., and dry it, &c., as before. A very black powder.—Dose, 1⁄ 4 to
1 gr.
Mercury, Precipitates of. 1. Black precipitate, Hahnemann’s
soluble mercury (basic mercurous and ammonium nitrate). 2. Green
p. (MERCURIUS PRÆCIPITATUS VIRIDIS, LACERTA VIRIDIS), from equal parts
of mercury and copper, separately dissolved in nitric acid, the
solutions mixed, evaporated to dryness, and then calcined until red
fumes cease to arise. Caustic. 3. Red p., mercuric oxide. 4. White p.,
ammonio-chloride of mercury.
Mercury, Ward’s. Syn. Ammonio-nitrate of mercury; Hydrargyri
ammoniæ nitras, L. To nitric acid, 4 parts, contained in a spacious bolt-
head or matrass, add, gradually, ammonium sesquicarbonate, 2
parts; afterwards add of mercury, 1 part, and digest in a gentle heat,
until the solution is complete.
Mercury with Chalk. Syn. Hydrargyrum cum Cretâ. Grey powder
(B. P.) Prep. Rub 1 oz. (by weight) of mercury, and prepared chalk, 2
oz., in a porcelain mortar, until metallic globules cease to be visible
to the naked eye and the mixture acquires a uniform grey colour.—
Dose. From 3 to 8 gr.
A little water is said to aid in the extinction of the mercury. Mr
Bottle suggests a slight departure from the Grey modus operandi
followed by the British Pharmacopœia in the above preparation. He
proposes to substitute for the tedious process of trituration in a
porcelain mortar the agitation of the mercury with the chalk in a
wide-mouthed glass bottle; by which means the metal may be
minutely subdivided, at a considerably less expenditure of time and
labour.
Mercury with Magnesia. (Ph. D.) Syn. Hydrargyrum cum
magnesiâ. Pure mercury, 1 oz., carbonate of magnesia, 2 oz. Rub
together in a porcelain mortar until the globules cease to be visible
and the mixture acquires a uniform, grey colour.—Dose, 3 to 8
grains.
Mercury, Yellow Oxide of. (Ph. B.) Syn. Hydrargyri oxydum
flavum. Prep. Perchloride of mercury, 4 oz.; solution of soda (Ph. B.),
2 pints; distilled water, q. s. Dissolve the perchloride in 4 pints of
distilled water, adding the solution by the application of heat, and
add this to the solution of soda. Stir them together, allow the yellow
precipitate to subside, remove the supernatant liquor by
decantation, thoroughly wash the precipitated oxide on a calico filter
with distilled water, and finally dry it by the heat of a water bath.
MES′LIN. A mixture of various kinds of grain. (Brande.)
METAGAL′LIC ACID. Obtained by heating dry gallic acid, by a
quick fire, to about 480° Fahr., or until it froths, melts, and becomes
black and solid, then dissolving the residuum in an alkali, filtering,
and precipitating by an acid. An insoluble, black powder.
ME′TAL. Syn. Metallum, L. See Metals.
METAL′LICA. [L.] Preparations of the metals. One of the
divisions of the Ph. L.
METAL′LIC TREES. See Vegetation (Metallic).
METAL′LO-CHROMES. A name given by Nobili to extremely
thin films of peroxide of lead deposited by electrolytic action upon
plates or polished steel, so as to produce an iridescent play of
colours. The effect is often very beautiful.
MET′ALLOIDS. A name sometimes applied to the NON-METALLIC
ELEMENTS.

METAL′LURGY. “The art of extracting metals from their ores,


and adapting them to various processes of manufacture.” (Percy.)
“Notwithstanding the striking analogy which exists between
common chemical and metallurgic operations, since both are
employed to isolate certain bodies from each other, there are
essential differences which should be carefully noted. In the first
place, the quantity of materials being always very great in
metallurgy, requires corresponding adaptations of apparatus, and
often produces peculiar phenomena; in the second place, the agents
to be employed for treating great masses must be selected with a
view to economy, as well as chemical action. In analytical chemistry,
the main object being exactness of result and purity of product, little
attention is bestowed upon the value of the reagents, on account of
the small quantity required for any particular process. But in
smelting metals upon the large scale, profit being the sole object,
cheap materials and easy operations are alone admissible.”[35]
[35] ‘Ure’s Dict. of Arts, Manufactures, and Mines,’ 4th edit.

The limits of this work do not permit of more than a general


reference to the leading operations of metallurgy under this head.
These are—digging, picking or sorting, stamping or crushing, and
washing, included under the general term, ‘dressing ore,’—roasting
or calcination, which is either performed with the fuel in contact with
the ore, or in reverberatory furnaces; and the liquation or reduction
to the reguline form. The application of these processes is noticed
under the leading metals. Those who desire to study the subject
minutely are referred to the treatises of Dr Percy, Robert Hunt,
Karsten, and Le Play.
MET′ALS. Syn. Metalla, L. Metals are elementary bodies, which
are generally distinguished by their lustre and power of conducting
heat and electricity. When their solutions are electrolysed, the metals
always appear at the electro-negative surface, and are hence termed
electro-positive elements.
Formerly, when science was much less advanced than at
present, the metals constituted a well-defined class. The properties
which were regarded as specially characteristic were physical, and
were not founded on chemical relations; thus, lustre and high
specific gravity were considered to be essential characters of all
metals. But we are now acquainted with metals which have a lower
specific gravity than water (lithium, sodium, &c.), and with so-called
non-metallic elements which present a strong metallic lustre (carbon
in the state of graphite, crystallised silicon). It will therefore be seen
that the term ‘metal’ is rather conventional than strictly scientific. By
far the greater number of elementary bodies at present known are
metals. Their physical characters and leading chemical properties are
noticed under each of them in its alphabetical place. The following
table exhibits some useful particulars:—

Table of some of the properties of some of the metals.


Names arranged in the order of their
Ductility. Malleability.
Gold. Gold.
Silver. Silver.
Platinum. Copper.
Iron. Tin.
Nickel. Platinum.
Copper. Lead.
Zinc. Zinc.
Tin. Iron.
Lead. Nickel.

Names arranged in the order of their


Power of Power of
conducting Heat. conducting Electricity.
Silver. Silver.
Copper. Copper.
Gold. Gold.
Tin. Zinc.
Iron. Iron.
Lead. Tin.
Bismuth. Lead.
Antimony.
Bismuth.

METANTIMON′IC ACID. H 4Sb 2O 7. The name given by M.


Fremy to that variety of antimonic acid obtained by decomposing
pentachloride of antimony with excess of water. It differs from
common antimonic acid in being tetra, and forming two different
classes of salts with the acids. The acid metantimoniate of potassium
is the only reagent which yields a precipitate with the sodium salts,
and is therefore of great value in chemical analysis. It is prepared by
fusing antimonic acid with excess of potassa, in a silver crucible,
dissolving the fused mass in a little cold water, and allowing it to
crystallise in vacuo. The resulting crystals (metantimoniate of
potassa), by solution in pure water, are resolved into free potassa
and the acid salt. See Antimony.
METAPEC′TIC ACID. See Pectin.
METAPEC′TIN. See Pectin.
METAPHOSPHOR′IC ACID. See Phosphoric acid.

METHEG′LIN. Syn. Hydromeli, H. vinosum, Mellis vinum, L. Prep.


From honey, 1 cwt.; warm water, 24 galls.; stir well until dissolved;
the next day add of yeast, 1 pint, and hops, 1 lb., previously boiled
in water, 1 gall.; along with water q. s. to make the whole measure 1
barrel; mix well, and ferment the whole with the usual precautions
adopted for other liquors. It contains on the average from 7% to 8%
of alcohol. See Mead.
ME′THYL. CH 3. The hypothetical radical of PYROXYLIC SPIRIT
(WOOD-SPIRIT, METHYLIC ALCOHOL) and the methyl series. It forms a
number of compounds analogous to those of ethyl.
METHYLAMINE. Syn. Methylia. CH 3H 2N. A colourless gas
possessing a very powerful odour of ammonia, and a strongly
alkaline reaction. It differs from ammonia, however, in being non-
inflammable. In other respects it bears a considerable resemblance
to it. Water at 55° Fahr. dissolves more than eleven hundred times
its bulk of methylamine. It may be easily condensed to a liquid by
means of a freezing mixture.
To obtain it nascent hydrogen is made to react on prussic or
formic acid. Methylia exists in herring brine, and is a frequent
product of the destructive distillation of substances containing
nitrogen. Most of its salts are very soluble in water.
METHYLATED SPIRIT. A mixture of 1 part of methylic alcohol
(wood spirit) and 9 parts of ethylic alcohol (spirit of wine). See
Spirit.
METHYLENE CHLORIDE. CH 2Cl 2. Syn. Methylene bichloride.
There are various methods of obtaining this compound:—1. By
heating chloroform with zinc filings and dilute sulphuric acid. 2. By
acting on methylene iodide with chlorine. In this process prolonged
treatment with chlorine, at ordinary temperatures, is required to
remove the last traces of iodine. (Buttlerow.) Chloride of methylene
is a colourless mobile fluid, having a smell like chloroform, and a
burning taste. It is used as an anæsthetic in place of chloroform.
According to Dr Armstrong, the substance known as METHYLENE
ETHER is a mechanical mixture of bichloride of methylene and ethylic
ether. Dr Richardson says of this latter it is not so quick in its action
as the methylene chloride, but that it is safer. See Anæsthetics.
METHYLIC ALCOHOL. See Wood Spirit.
MEZE′REON. Syn. Garou; Mezereon bark, Mezerei cortex (B. P.);
Mezereon—Ph. L., E., & D. The dried bark of the Daphne Mezereum,
mezereon; or Daphne Laureola, spurge, or wood-laurel. The “bark of
the root of Daphne Mezereum,” or spurge olive. (Ph. L.) A stimulant
and diuretic. It is employed as a sudorific and alterative, in syphilis,
rheumatism, scrofula, and chronic cutaneous diseases, usually in
conjunction with sarsaparilla. It has also been used as a masticatory
in toothache, paralysis of the tongue, &c. On the Continent it is used
as a vesicant. For this purpose it is softened by soaking it in hot
vinegar, and is then bound on the part, and renewed after intervals
of some hours, until vesication is produced.
MICE. See Rats.
MI′CROSMIC SALT. NaNH 4HPO 4, Syn. Tribasic phosphate of
sodium and ammonium. Prep. 1. Phosphates of soda and ammonia,
equal parts; water, q. s.; dissolve separately, mix the solutions,
evaporate, and crystallise. A slight excess of phosphate of ammonia
aids the crystallisation.
2. (Fownes.) Phosphate of sodium, 6 parts; water, 2 parts;
liquefy by heat, and add of sal ammoniac (in powder), 1 part;
common salt separates, and after its removal the liquid is
concentrated so that crystals may form. Used as a flux in blowpipe
assays.
MI′CROSCOPE. The value of the microscope in chemistry and
the collateral sciences is now so generally acknowledged that it
would be folly to do more than merely allude to the subject here.
In the COMPOUND MICROSCOPE, which has quite superseded the
‘simple microscope’ as an instrument of research, the object is
magnified in the first instance by the object-glass, and then
remagnified by the eye-piece. It follows, therefore, that the
magnifying power of the instrument may be increased either by
increasing the power of the object-glass or that of the eye-piece. It
must be borne in mind, however, that in increasing the power of the
eye-piece we do not magnify the object itself in a greater degree,
but simply increase the image of the object formed by the object-
glass. Any imperfections which may exist in the latter are thus
greatly increased. At first the great drawback to the use of the
compound microscope was its deficiency in achromatism; but the
researches of Mr Lester and Dr Goring led to the achromatising of
the object-glass, which was the first of the rapid strides towards
perfection made by this instrument during the last twenty years. The
two most useful object-glasses are the ‘quarter-inch,’ which should
magnify from 200 to 220 diameters, and the ‘inch,’ which should
magnify from 30 to 40 diameters. The definition of these glasses
should be good, and they should transmit plenty of light. Any lines in
a structure examined by them should appear sharp and distinct, and
there should be no coloured fringes around the object. It is of great
importance that the object-glasses are kept perfectly free from dust.
A few shreds of wash-leather of the finest quality should be kept in a
pill-box for cleaning them. Before rubbing them with the leather they
may be breathed upon, but no whiting or liquid of any kind should
be used, as each object-glass, being achromatic, is a very delicate
piece of workmanship, consisting of two lenses of flint and crown-
glass cemented together by Canada balsam. Compound microscopes
are now sold by the best London makers at very low prices. A really
good instrument, adapted to most of the wants of the chemical,
pharmaceutical, or medical student, may be obtained for five
guineas.
The following formulæ for the preparation of the chief
substances, together with the principal reagents required in the
working of the microscope, are from Dr Lionel Beale’s valuable book,
‘How to Work with the Microscope,’[36]
[36] Harrison, 59, Pall Mall.

Reagents—
1. Alcohol, of various strengths.
2. Ether, to dissolve oil globules.
3. Nitric acid (1 part of strong acid to 5 of water)
4. Sulphuric acid (1 to 5).
5. Hydrochloric acid.
6. Acetic acid, glacial and dilute (1 to 5).
7. Chromic acid, very dilute, to harden tissues.
8. Solution of potash, saturated and dilute (1 to 10).
9. Solution of soda (25 gr. of fused soda to 1 oz.).
10. Ammonia (1 part of the strongest solution to 3 of water).
11. Nitrate of baryta, a cold saturated solution of.
12. Nitrate of silver (120 gr. to 2 oz.). These two are for the
mineral acids.
13. Oxalate of ammonia in solution. Test for lime.
14. Solution of iodine saturated, i.e. 1 to 7000 parts of water.
Another solution is—1 gr. of iodine and 3 of iodide of potassium in 1
oz. of distilled water.
1. Cements.—1. Brunswick Black. Boil together 1⁄ 4 lb. foreign
asphaltum and 4 1⁄ 4 oz. of linseed oil (previously thickened with
litharge), then mix to a proper consistence with oil of turpentine
(about 1 pint).
2. Gold Size. Boil 25 parts of linseed oil with 1 of minium and
1⁄ 3rd part of umber for 3 hours; pour off the clear fluid, and mix
with equal parts of powdered white lead, and yellow ochre, added in
small successive portions. Then boil well the whole again, and pour
off the clear fluid. It dries slowly, but firmly. Both this and the last
are dissolved by turpentine.
3. Goadby’s Marine Glue. Dissolve separately in coal naphtha
equal parts of shell-lac and india rubber. Mix thoroughly with heat.
4. Sealing-wax Varnish. Dissolve the best sealing-wax in enough
strong spirit of wine to reduce it to the proper consistence. This is
brittle.
5. Canada Balsam. This dries spontaneously.
Solutions of shell-lac, gum, and various other cements and glues
are employed by microscopic manipulators.
Preservative Fluids. Canada balsam, spirit and water, glycerin,
solution of gelatin, saturated solution of alum, chloride of zinc, and
chloride of calcium, are all used to preserve microscopic objects.
The following formulæ will be found useful:—
1. Goadby’s Solution. Bay salt, 4 oz.; alum, 2 oz.; corrosive
sublimate, 4 gr.; boiling water, 4 pints. Mix and filter. It may often be
more diluted.
2. Thwaite’s Fluid. Mix spirit of wine, 1 oz., with creosote
sufficient to saturate it; rub up with chalk to form a thin paste, and
mix gradually with 16 oz. of water. To this may be added an equal
quantity of water, saturated with camphor.
3. Simple Creosote Solution. Dissolve creosote, 1 dr., in
pyroligneous acid, 1 dr., and mix gradually with cold water, 1 pint.
4. Passini’s Solution. For blood-globules, nerves, and white
tissues generally. Perchloride of mercury, 1 part; chloride of sodium,
2 parts; glycerin, 13 parts; distilled water, 113 parts.
MIL′DEW. Syn. Rust, Blight. The mouldy appearance on the
leaves of plants produced by innumerable microscopic fungi. The
hop, wheat, and the choicest garden fruit trees, are those most
commonly attacked. The causes are said to be excess of moisture,
and absence of the free circulation of air and sunshine. On the small
scale, finely powered sulphur is occasionally dusted over the parts
affected, as a remedy.
MIL′IARY FEVER. Syn. Miliaria, L. Among the other symptoms
are—anxiety and frequent sighing, the perspiration has a strong and
peculiar smell, and there is a sensation of pricking on the neck and
breast, followed by an eruption of small red pimples, which in two or
three days become white vesicles, dry up, peel off, and are
succeeded by others. The moist weather of spring and autumn are
the periods in which it is most prevalent; and delicate females,
particularly in child-bed, are those most liable to its attacks.
Sometimes it assumes a malignant character. The treatment of this
affection consists chiefly in combating the depression of the system
by a supporting diet; but everything that heats or stimulates the skin
should be avoided. The apartment should be kept cool and well
ventilated, and cooling saline laxatives and bitter tonics, with cooling
drinks, should also be had recourse to.
MILK. Syn. Lac, L. The value of milk as an article of food is
clearly shown by the fact of it being sufficient to support, and to
increase the growth of, the young of every species of the mammalia;
at once supplying materials for the formation of the osseous, fleshy,
and liquid portions of the body. “The substances present in milk are
wonderfully adapted to its office of producing materials for the rapid
growth and development of the animal frame. It contains an
azotised matter, casein, nearly identical in composition with muscular
flesh, fatty principles, and a peculiar sugar, and, lastly, various salts,
among which may be mentioned phosphate of lime, held in
complete solution in a slightly alkaline liquid.
“The white and almost opaque, appearance of milk is an optical
illusion. Examined by a microscope of even moderate power, it is
seen to consist of a perfectly transparent fluid, in which float about
numbers of minute transparent globules; these consist of fat
surrounded by an albuminous envelope, which can be broken
mechanically, as in the churning, or dissolved by the chemical action
of caustic potassa, after which, by agitating the milk with ether, the
fat can be dissolved.” (Fownes.)
Comp. Cows’ milk, of average quality, contains from 10% to 12%
of solid matter when evaporated to dryness by steam heat, and has
the mean sp. gr. 1·030; while that of the skimmed milk is about
1·035; and of the cream, 1·0244. (Ure.) The average CREAM of cows’
milk contains 4·5% of butter, 3·5% of curd, and 92% of whey.
(Berzelius.) The SKIMMED MILK consists of water, 92·9%; curd, 2·%;
sugar of milk, 3·5%; lactic acid, lactate of potassa, and a trace of
lactate of iron, ·6%, chloride of potassium, phosphate of potassa,
and earthy phosphates (lime), ·2%. (Berzelius.)
The following analysis of fresh milk is by M. Haidlen:—

Water 873·00
Butter 30·00
Casein 48·20
Milk sugar 43·90
Phosphate of lime 2·31
Phosphate of magnesia ·42
Phosphate of iron ·07
Chloride of potassium 1·44
Chloride of sodium ·24
Soda in combination with casein ·42
————
1000.

Professor Wanklyn has devised and published in his excellent


little manual ‘Milk Analysis’[37] a process by which a very thorough
chemical examination of milk may be accomplished with great facility
and expedition.
[37] Trubner and Co.

In his preliminary remarks he condemns, as utterly unreliable


and misleading, the inferences to be drawn from those hydrometric
instruments, the lactometer or lactodensimeter, and creamometer. “A
very little consideration,” he says “will suffice to make intelligible the
obliquity of the indications of the lactometer and to show how
untrustworthy it must be. The lactometer, as of course will be
understood, is simply the hydrometer applied to milk; and readings
of the instrument are neither more nor less than specific gravities.
The more milk-sugar, and casein, and mineral matter there is in a
given specimen of milk, the greater (other things being equal) will
be its density or specific gravity, and the higher the lactometer
reading.
“If, however, fat globules (as happens in the instance of milk) be
diffused through the fluid, then, because fat is lighter than water, the
effect of the other milk solids on the gravity of the liquid, will be
more or less neutralised. The density of milk-fat is about 0·9, water
being 1·0. Now, if a solution of casein and milk-sugar, of specific
gravity 1·030, be sufficiently charged with fat globules, its specific
gravity may be sent down even below the gravity of water. How
much would be required to bring about such a result is a matter of
simple calculation.
“This being understood, it will be obvious that if the specimens
of milk differ in specific gravity, there must be two distinct and
equally valid ways of accounting for the difference.
“The milk with the lower gravity may be milk let down with
water, or let down with fat, i. e. milk let down by being enriched.”
In support of this last assertion Professor Wanklyn quotes
corroborative instances afforded by the examination of different
specimens of milk known as ‘strippings,’ these being the last portions
of milk yielded by the cow at the termination of the milking. All these
‘strippings’ had a lower specific gravity than normal milk.
Further, Professor Wanklyn points out that the specific gravity of
organic fluids is a fallacious index of the amount of solids they may
contain, as is illustrated by the fact, that whilst a 10 per cent.
solution of chloride of potassium has a specific gravity of 1·065 at
15° C., and a 10 per cent. solution of casein and milk sugar, has a
specific gravity of only about 1·035.
The creamometer meets with equal condemnation in Professor
Wanklyn’s little book, since different specimens of milk vary
considerably in their yield of cream, and a perfectly pure sample of
milk may yield less cream than one which has been tampered with.
A complete analysis of milk involves the determination of the
water, the fat (the essential constituent of the cream), the casein,
milk-sugar, and ash.
The following is an outline of Professor Wanklyn’s neat and
ingenious method of analysis:—
By means of an accurately graduated pipette, he first places 5
cubic centimetres of the milk in a small weighed platinum dish
(about 14 grammes in weight) just previously ensuring the sample
from which the milk is taken being thoroughly mixed.
The dish is then placed over a water-bath (the water in which
must be kept vigorously boiling the whole time) for three hours, at
the end of which time all the water having been driven off, there will
remain in the dish a completely dried up residue.
The increase in weight between the empty dish and the residue,
will give the weight of the ‘milk solids’ from 5 c.c. of milk. Of course,
if this weight be multiplied by 20, the yield from 100 c.c. of milk will
be obtained.
To reduce this to a percentage statement it is necessary to
remember that 100 c.c. of average milk weigh 102·9 grammes. The
next proceeding consists in the determination of the fat. This is done
by treating the dried milk solids resulting from the 5 c.c. of milk with
ether. There are several important minutiæ necessary to be observed
in connection with this part of the process, for the particulars of
which the reader is referred to Professor Wanklyn’s book. Suffice it
to say, that if properly performed, the whole of the fat is dissolved
by the ether, and being separated from the non-fatty portion of the
residue is weighed and calculated as ‘fat.’
If, then, the amount found as fat be deducted from the whole of
the milk solids previous to their treatment with ether, the ‘milk
solids, not fat,’ will be arrived at. Professor Wanklyn estimates the
casein[38] as follows:—He treats the milk solids, not fat, with hot
alcohol, by which means he dissolves out from them, and removes
the milk-sugar and the soluble chlorides. The remaining residue,
consisting of casein and phosphate of sodium (chemically combined
with the casein), is dried on a water-bath until it ceases to lose
weight. It is then weighed along with the vessel containing it, and
ignited. The combined weight of the vessel and phosphate of sodium
remaining after ignition being deducted from the weight previous to
ignition, the difference is the casein.
[38] Under the head “Casein” Prof Wanklyn includes the
entire nitrogenous materials of milk.
Another and quicker method, recommended by Professor
Wanklyn, for the determination of the casein, is to measure it by the
amount of albuminoid ammonia it is capable of yielding when
subjected to the ‘albuminoid ammonia process,’ invented by Messrs
Wanklyn, Chapman, and Smith.
The alcoholic solution filtered off from the combined casein and
phosphate of sodium, contains the milk sugar and soluble chlorides.
It is evaporated to dryness on a water-bath, and the residue with
the vessel containing it, is weighed. It is then gently ignited, and the
weight of the remaining residue being deducted from the total
weight before ignition, gives the yield of milk sugar. Or the milk
sugar may be determined by titration with a standard copper
solution.
For the determination of the ash it is only necessary to ignite
the milk solids from 5 c.c. of milk, in the small platinum dish, by
which operation all the organic matter being driven off, that which
remains behind constitutes the ‘ash’ and is weighed as such.
It will be obvious that in order to determine with anything like
rigid accuracy the quality of any sample of milk by analysis, not only
must a normal standard for the purpose of comparison be adopted,
but such normal standard must represent very closely and with but
little variation the definite composition of all sound and genuine milk.
Professor Wanklyn says that “the following, which is the result
of several concordant analyses of country-fed milk, may be taken as
representing normal milk. In 100 grammes of milk—

Solids
12·5 grammes.
(dry at 100° C)
Water 87·5
———
100·0
“The 12·5 grammes consist of 9·3 grammes of ‘solids which are
not fat,’ and 3·2 grammes of fat.” The above data, which are
founded on the examination of a very large number of different
samples of milk, are confirmed by the researches of Müller and
Eisenstuck, who were employed by the Royal Agricultural Society of
Sweden in a similar investigation. The labours of these chemists
extended over a twelvemonth, and the result of them was to show
that the milk yielded day by day, for a whole year, by a herd of cows
was remarkably constant in composition.
Professor Wanklyn gives the following formulæ for the
calculation and statement of the results of milk analysis. He says,
treating the question quite rigidly, which I believe is the proper way
of dealing with it, we arrive at the following:—
Problem 1. Given the percentage of ‘solids, not fat’ (= a), in a
specimen of sophisticated milk (i. e. milk, either watered, or
skimmed, or both)—required the number of grammes of genuine
milk which was employed to form 100 grammes of it.
Answer. Multiply the percentage of ‘solids, not fat’ by 100, and
divide by 9·3.

Or— (100 / 9·3)a.

Problem II.—Given the percentage of ‘solids, not fat’ (= a), also


the percentage of fat (= b), in a specimen of sophisticated milk—
required the number of grammes of fat which have been removed
by skimming from the genuine milk which was employed to form 100
grammes of it.

Answer.— (3·2 / 9·3)(a - b).

In translating fat into cream, the rule is that a removal of 0·2


gramme of fat equals a removal of 1·0 gramme of cream. This rule
is directly founded on experiment. I do not, however, claim a high
degree of accuracy for the measurement of the cream.
Finally, a slight refinement may be noticed. If a specimen of
sophisticated milk has been produced by both skimming and
watering, it will be obvious, on consideration, that the extraneous
waters employed in manufacturing 100 grammes of it is equal to the
difference between 100 and the quantity of genuine milk employed
to make 100 grammes of sophisticated milk, together with a quantity
of water equal to that of fat removed by skimming.

Extraneous water = 100(100 / 9·3)a + (3·2 / 9·3)(a -


b)
= 100[(100 + 3·2) / 9·3](a - b)

Save for the purpose of finding out the presence of matters


other than an excess of water in the milk (a contingency regarded as
very improbable), the estimation of the casein and milk sugar is
unnecessary. The determination of the ash is for the object of
learning if foreign mineral matters, such as chalk or any other
inorganic impurity, are present. Professor Wanklyn says he believes
that such like extraneous bodies are never employed. The chief, if
not the sole, form of dishonesty are watering and skimming.
The amount of ash, however, is a good criterion as to the extent
of dilution that has been practised, a deficient amount being, of
course, confirmatory of a watered milk.
The determination of the amount of ‘solids, not fat,’ is, in almost
every instance, all that is necessary to enable an opinion to be
arrived at as to whether the sample of milk has had water added to
it or not.
Out of fifty-six samples of milk supplied to the different London
unions in 1873, Professor Wanklyn reports that he found only fifteen
unwatered, or nearly unwatered. Of these fifteen samples nine had
been skimmed, leaving only six that were at once unwatered and
unskimmed. These figures, therefore, show that only about 10 per
cent. of the milk supplied in the above year to the Metropolitan
unions was genuine. He adds—“It is curious to compare the
language of the contract under which (as it appears from Mr
Rowsell’s report) the dealer supplied the various unions with milk,
with the quality of the article as exhibited by the analysis. ‘New
unskimmed milk unadulterated,’ ‘genuine as from the cow,’ ‘best new
unskimmed milk, to produce 10 per cent. of cream,’ occur in these
contracts.”
Prop. These are well known. Perfectly fresh milk is slightly
alkaline, but soon becomes acid on exposure to the air, and after a
time white coagula of casein (CURDS) separate from it. This change is
immediately effected by the addition of rennet or an acid. That from
the first, when dried and pressed, constitutes cheese.
Pur., Tests, &c. The common frauds practised by the milk-
dealers are the addition of water and the subtraction of part of the
cream. Sometimes potato starch is added to the milk, to give it a
creamy or rich appearance, and this addition is still more frequently
made to cream, to increase its consistence and quality.
The presence of potato starch may be determined by boiling
some of the milk with a little vinegar, and after separating the
coagulum by a strainer, and allowing the liquid to become cold,
testing it with solution or tincture of iodine. If it turns blue, starch,
flour, or some other amylaceous substance, has been used to
adulterate it. In most cases it will be sufficient to apply the test to
the unprepared suspected milk.
It has frequently been stated that chalk, plaster of Paris, gum,
gelatin, sugar, flour, mucilage of hemp-seed, the brains of animals,
and other similar substances, are often added to London milk, but
there is no reason to suppose there is any truth in these assertions,
as some of these articles are too costly to be used, and the presence
of others would so alter the flavour or appearance of the milk, or
would so soon exhibit themselves by subsidence, as to lead to their
detection.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like