Lumen Programming Guide Writing PHP Microservices REST and Web Service APIs 1st Edition Paul Redmond (Auth.) download
Lumen Programming Guide Writing PHP Microservices REST and Web Service APIs 1st Edition Paul Redmond (Auth.) download
https://textbookfull.com/product/lumen-programming-guide-writing-
php-microservices-rest-and-web-service-apis-1st-edition-paul-
redmond-auth/
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/
https://textbookfull.com/product/integrating-web-services-with-
oauth-and-php-a-php-architect-guide-1st-edition-matthew-frost/
https://textbookfull.com/product/php-8-quick-scripting-reference-
a-pocket-guide-to-php-web-scripting-third-edition-mikael-olsson/
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/
https://textbookfull.com/product/programming-php-4th-edition-
peter-macintyre/
https://textbookfull.com/product/pro-restful-apis-design-build-
and-integrate-with-rest-json-xml-and-jax-rs-patni/
https://textbookfull.com/product/php-and-mysql-for-dynamic-web-
sites-fifth-edition-ullman/
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
v
Contents
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
vii
■ CONTENTS
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
ix
■ CONTENTS
x
About the Author
xi
About the Technical Reviewer
xiii
Acknowledgments
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.
xvii
■ INTRODUCTION
Code Examples
A typical PHP code snippet looks like this:
To guide readers, approximate line numbers are used when you will be adding a block of code to an
existing class or test file:
Longer lines end in a backslash (\) and continue to the next line:
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.
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.
OK (1 test, 4 assertions)
1
https://laravel.com/docs/homestead
xviii
■ INTRODUCTION
This is an aside
Hey, Listen! Tips give you pointers related to concepts in the book.
Need the Info This aside provides additional info related to code and concepts.
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.
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.
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).
Once you finish the Homestead installation instructions you should be able to ssh into the virtual
machine (Listing 1-2).
* 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
Once the installation finishes, verify that you have the right version of PHP in your path (Listing 1-4).
Next, you need to install the MySQL database server with Homebrew (Listing 1-5).
Once the MySQL installation is finished, make sure you can connect to the database server (Listing 1-6).
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).
# 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).
# 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
Once MySQL is installed, you should set a root password (Listing 1-10).
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.
# 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).
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.
Verify that you can connect to MySQL after you finish installing MySQL and setting a root password
(Listing 1-15).
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.
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.
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).
Replace it with the code in Listing 2-3 and save the file.
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).
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.
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
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.
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).
9
CHAPTER 2 ■ HELLO LUMEN
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).
Route Parameters
The second route you are going to add has a dynamic route parameter (Listing 2-10).
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.
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.
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.
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).
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.
With facades enabled, the new middleware will add a log entry to storage/logs/lumen.log for every
request (Listing 2-15).
■ 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).
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.
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.
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.
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.
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.
textbookfull.com