This document provides instructions for building a simple notepad application that allows users to store and search text notes in the cloud using a mobile or desktop web browser. The application uses MongoDB for document storage, the Slim PHP micro-framework for application logic, and Bootstrap for a responsive user interface. The steps outlined include setting up the basic application structure with Slim, creating a MongoDB database to store notes, building a form to add and edit notes, and deploying the application on IBM Bluemix.
Customize it! Make IBM Connections look your way Klaus Bild
My session at Dominopoint Days 2013 in Milano
IBM Connections offers endless customizing possibilities in order to change the platform according to your needs . In this session we will explore the many customization options available and will look at some examples like customizing the UI, notifications, blog themes, profiles or even metrics reports.
This will give you an idea of the various possibilities Connections is offering and should act as a starting point for your own customizations.
Introducing the JotSpot Data Model and APIScott McMullan
This preso introduces the benefits of adding structure to wikis and introduces how this is done in JotSpot wikis. It also provides a quick fly-over of the JotSpot API.
Customize it! Make IBM Connections look your way Klaus Bild
My session at Dominopoint Days 2013 in Milano
IBM Connections offers endless customizing possibilities in order to change the platform according to your needs . In this session we will explore the many customization options available and will look at some examples like customizing the UI, notifications, blog themes, profiles or even metrics reports.
This will give you an idea of the various possibilities Connections is offering and should act as a starting point for your own customizations.
Introducing the JotSpot Data Model and APIScott McMullan
This preso introduces the benefits of adding structure to wikis and introduces how this is done in JotSpot wikis. It also provides a quick fly-over of the JotSpot API.
Recently we presented on WordCamp Thessaloniki how we can use WordPress as a Framework. In this presentation you can find some nice ideas on what is a Framework, how WordPress can be used as one and how we can start building custom apps using WordPress. Enjoy!
To create a project with node.js either for mobile applications to access data or for various clients based websites which requires accessing data; it requires building a basic API. These projects, mostly built with express.js and a mango database. In this article we will understand
the basic of Node.js, express middleware and API creation/Restful web services using Node.js with one basic example.
Cloud Community Engineering - Holiday readinessOleg Posyniak
In this presentation, B. Korablov, B. Batschelet, and O. Posyniak will provide an overview on how to prepare your Magento Cloud environment for Holidays
Extending An Android App Using the IBM Push for Bluemix Cloud ServiceIBM developerWorks
Bluemix is IBM's open cloud platform. More importantly, it's an app developer's best friend. It lets you focus on building outstanding web and mobile apps -- while it takes care of the infrastructure setup, provisioning, and hosting details for you. Learn how to quickly extend your Android app using the IBM Push for Bluemix cloud service.
PhoneGap (aka Cordova) is a cross-platform framework for developing mobile apps using standard web development tools like HTML, CSS, and JavaScript. Join Troy Miles to learn how to create mobile apps with PhoneGap by building a simple but full-featured app during this hands-on class. Troy explores PhoneGap’s important capabilities, including GPS, camera, and audio recordings. Because JavaScript has a reputation as a somewhat difficult language, Troy teaches techniques for keeping your code robust and clean. To give your app the appropriate look and feel for the device on which it is running, the class will use the open source Chocolate Chip UI framework for testing. Troy shares ways to debug the code by running it as a web app, using browser development tools, or as a phone app, using the Chrome browser’s remote debugging features. Leave with the basics you need to start building your own cross-platform mobile apps.
This book is crafted for beginner coders seeking to delve into the realm of web app development using Python, specifically focusing on deploying applications with Replit.
Whether you aim to create a profitable venture or simply desire to enhance your skills in building and deploying web applications, this guide is tailored for you.
Our web application will be a straightforward yet powerful AI writer tool aimed at helping Users get special copy for their businesses based on a big Ad Men using OpenAI's API.
Buy full book here:
https://www.amazon.com/dp/B0CSPV74XK
MobiCloud: Towards Cloud Mobile Hybrid Application Generation using Semantica...Amit Sheth
Ajith Ranabahu, Amit Sheth, Ashwin Manjunatha, and Krishnaprasad Thirunarayan, 'Towards Cloud Mobile Hybrid Application Generation using Semantically Enriched Domain Specific Languages', International Workshop on Mobile Computing and Clouds (MobiCloud 2010), Santa Clara, CA,October 28, 2010.
Paper: http://knoesis.org/library/resource.php?id=865
Project: http://knoesis.wright.edu/research/srl/projects/mobi-cloud/
iOS development Crash course in how to build an native application for iPhone.
i will be start from beginning till publishing on Apple Store step by step.
this session # 4
Lecture on CodeIgniter, # OSS Essential Training Program at Chittagong University of Engineering Technology, February 2008, http://bdosdn.org/wsatcuet.php
IBM SoftLayer - eSofties Solutions Ltd.Carlos Tomas
eSofties Solutions Ltd. – Cuts delivery times and reins in installation costs with a SoftLayer solution
Cuts deployment times
for on-premises installations from weeks or months to a matter of seconds using a self-service portal
Eliminating downtime and enhancing service with a SoftLayer cloud platform.
Business benefits:
Eliminates downtime and improves service with SoftLayer technology designed for dependable performance
Reduces IT burden and frees IT staff to focus on business-critical activities
Enhances value proposition by backing its offering with a trusted global cloud hosting brand
More Related Content
Similar to Build a notepad application with PHP, MongoDB, and IBM Bluemix - by Vikram Vaswani
Recently we presented on WordCamp Thessaloniki how we can use WordPress as a Framework. In this presentation you can find some nice ideas on what is a Framework, how WordPress can be used as one and how we can start building custom apps using WordPress. Enjoy!
To create a project with node.js either for mobile applications to access data or for various clients based websites which requires accessing data; it requires building a basic API. These projects, mostly built with express.js and a mango database. In this article we will understand
the basic of Node.js, express middleware and API creation/Restful web services using Node.js with one basic example.
Cloud Community Engineering - Holiday readinessOleg Posyniak
In this presentation, B. Korablov, B. Batschelet, and O. Posyniak will provide an overview on how to prepare your Magento Cloud environment for Holidays
Extending An Android App Using the IBM Push for Bluemix Cloud ServiceIBM developerWorks
Bluemix is IBM's open cloud platform. More importantly, it's an app developer's best friend. It lets you focus on building outstanding web and mobile apps -- while it takes care of the infrastructure setup, provisioning, and hosting details for you. Learn how to quickly extend your Android app using the IBM Push for Bluemix cloud service.
PhoneGap (aka Cordova) is a cross-platform framework for developing mobile apps using standard web development tools like HTML, CSS, and JavaScript. Join Troy Miles to learn how to create mobile apps with PhoneGap by building a simple but full-featured app during this hands-on class. Troy explores PhoneGap’s important capabilities, including GPS, camera, and audio recordings. Because JavaScript has a reputation as a somewhat difficult language, Troy teaches techniques for keeping your code robust and clean. To give your app the appropriate look and feel for the device on which it is running, the class will use the open source Chocolate Chip UI framework for testing. Troy shares ways to debug the code by running it as a web app, using browser development tools, or as a phone app, using the Chrome browser’s remote debugging features. Leave with the basics you need to start building your own cross-platform mobile apps.
This book is crafted for beginner coders seeking to delve into the realm of web app development using Python, specifically focusing on deploying applications with Replit.
Whether you aim to create a profitable venture or simply desire to enhance your skills in building and deploying web applications, this guide is tailored for you.
Our web application will be a straightforward yet powerful AI writer tool aimed at helping Users get special copy for their businesses based on a big Ad Men using OpenAI's API.
Buy full book here:
https://www.amazon.com/dp/B0CSPV74XK
MobiCloud: Towards Cloud Mobile Hybrid Application Generation using Semantica...Amit Sheth
Ajith Ranabahu, Amit Sheth, Ashwin Manjunatha, and Krishnaprasad Thirunarayan, 'Towards Cloud Mobile Hybrid Application Generation using Semantically Enriched Domain Specific Languages', International Workshop on Mobile Computing and Clouds (MobiCloud 2010), Santa Clara, CA,October 28, 2010.
Paper: http://knoesis.org/library/resource.php?id=865
Project: http://knoesis.wright.edu/research/srl/projects/mobi-cloud/
iOS development Crash course in how to build an native application for iPhone.
i will be start from beginning till publishing on Apple Store step by step.
this session # 4
Lecture on CodeIgniter, # OSS Essential Training Program at Chittagong University of Engineering Technology, February 2008, http://bdosdn.org/wsatcuet.php
IBM SoftLayer - eSofties Solutions Ltd.Carlos Tomas
eSofties Solutions Ltd. – Cuts delivery times and reins in installation costs with a SoftLayer solution
Cuts deployment times
for on-premises installations from weeks or months to a matter of seconds using a self-service portal
Eliminating downtime and enhancing service with a SoftLayer cloud platform.
Business benefits:
Eliminates downtime and improves service with SoftLayer technology designed for dependable performance
Reduces IT burden and frees IT staff to focus on business-critical activities
Enhances value proposition by backing its offering with a trusted global cloud hosting brand
Targeting worldwide growth with a tailor-made cloud solution from IBM and SAP
Business benefits:
50% faster time-to-market for new hat designs
Integrates complex business processes based on industry best practices
Supports global growth by enabling Grace to scale out cost-effectively
A photo sharing app service in Italy achieves rapid time to market, facilitates affordable resource deployments and gets a better handle on usage spikes generated by promotional initiatives and expanding volumes when it works with IBM Advanced Business Partner Beck et al. Services and adopts a SoftLayer infrastructure. “A startup in Italy needs a lot of friends who put their faith in you and help you develop a successful offering. One of our trusted friends is IBM." client's quote."
Copenhagen business school drives sustainability at roskilde festival using c...Carlos Tomas
A nonprofit humanitarian organization in Denmark gains faster insights into crowd movements and sales data, supporting sustainability, achieves smart optimization of safety, catering, energy, water and waste management and increases scalability with cloud- based analytics and a cloud- based Big Data lab on IBM Bluemix, IBM SPSS and IBM Watson Analytics technologies, running on a SoftLayer infrastructure, to seamlessly correlate data from multiple sources.
Ibm mobility services - Supporting the mobile workforceCarlos Tomas
Highlights
• Highly customisable bespoke solutions
• Maximising availability
• Reducing cost and complexity
• Covering a comprehensive range of
multivendor devices
• Single supplier and point of contact
Case Study: Putting The Watson Developer Cloud to Work - by Doron Katz & Luci...Carlos Tomas
See the source code and thinking behind NewsMedia
Inc.’s (a fictitious company) implementation of the deep
learning and natural language processing APIs available
on Watson Developer Cloud.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
2. developerWorks® ibm.com/developerWorks/
Build a notepad application with PHP, MongoDB, and IBM
Bluemix
Page 2 of 10
In this tutorial, I'll walk you through the process of building a simple notepad application that lets
users store and search free-form text notes in the cloud using a mobile or desktop web browser. I'll
also show you how to deploy and run the application on the IBM Bluemix® cloud platform.
What you'll need
The example notepad application allows users to create and enter an unlimited number of text
notes, and also edit, search, and delete notes. In addition, users can color code notes for easy
categorization or identification.
On the client, I'll use Bootstrap to create a mobile-friendly user interface for the application. On
the server, I'll use Slim, a PHP micro-framework, to manage the application flow and connect and
retrieve data from MongoDB.
To follow the steps in this article, you will need:
• A basic familiarity with Bootstrap, PHP, and MongoDB
• A local PHP development environment with either Apache (with mod_rewrite and .htaccess
file support) or nginx
• A local or remote deployment of MongoDB with a configured database, user, and password;
you can obtain a free or paid deployment of MongoDB by registering for a MongoLab account
• A Bluemix account (register for your free trial account or log in to Bluemix if you already have
an account)
• Composer, the PHP dependency manager
• The CloudFoundry command-line tool
• A text editor or IDE
“ This notepad application uses MongoDB for fast and
scalable document storage, the Slim PHP micro-framework
for business logic, and Bootstrap for a responsive, mobile-
friendly user interface. ”
Get the code on GitHub
Step 1. Create the bare application
1. The first step is to create a bare application containing the Slim PHP micro-framework. You
can download and install it by using Composer, the PHP dependency manager. Use this
Composer configuration file, which should be saved to <$APP_ROOT>/composer.json (<
$APP_ROOT> refers to your project directory):
{
"require": {
"slim/slim": "2.*"
}
}
2. Install Slim using Composer with the following command:
shell> php composer.phar install
3. Next, set up the main control script for the application. This script will load the Slim framework
and initialize the Slim application. It will also contain callbacks for each of the application's
3. ibm.com/developerWorks/ developerWorks®
Build a notepad application with PHP, MongoDB, and IBM
Bluemix
Page 3 of 10
routes, with each callback defining the code to be executed when the route is matched to
an incoming request. Because the application must support listing, viewing, adding, editing,
deleting, and searching notes, you can define the URL routes /index, /view, /save, and /
delete as shown below. Save this script as <$APP_ROOT>/index.php.
<?php
// use Composer autoloader
require 'vendor/autoload.php';
require 'config.php';
// configure Slim application instance
// initialize application
$app = new SlimSlim(array(
'debug' => true,
'templates.path' => './views'
));
$app->config = $config;
// index page handlers
$app->get('/', function () use ($app) {
$app->redirect($app->urlFor('index'));
});
// handler to list available notes in database
// if query string included
// filter results to match query string
$app->get('/index', function () use ($app) {
// code here
})->name('index');
// handler to display add/edit form
$app->get('/save(/:id)', function ($id = null) use ($app) {
// code here
});
// handler to process form input
// save note content to database
$app->post('/save', function () use ($app) {
// code here
});
// handler to delete specified note
$app->get('/delete/:id', function ($id) use ($app) {
// code here
});
// handler to display specified note
$app->get('/view/:id', function ($id) use ($app) {
// code here
});
// hook to add request URI path as template variable
$app->hook('slim.before.dispatch', function() use ($app) {
$app->view()->appendData(array(
'baseUri' => $app->request()->getRootUri()
));
});
$app->run();
4. Notice the 'slim.before.dispatch' hook, which retrieves the current request URL (including
any sub-directory paths) and makes it available as a template variable named $baseUri. This
maximizes portability, as it allows you to move your application to a different directory path on
4. developerWorks® ibm.com/developerWorks/
Build a notepad application with PHP, MongoDB, and IBM
Bluemix
Page 4 of 10
the web server without needing to rewrite the URL paths in your views. You can see this in
action in the various templates in the source code repository.
5. You will also need to construct a base user interface that can be used for the various views
rendered by the app. Here's an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cloud Notepad</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/
bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-
theme.min.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="panel panel-default">
<div class="panel-heading clearfix">
<h4 class="pull-left">Notes</h4>
</div>
</div>
<!-- page content here -->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
With all the pieces in place, you can now start building out the application itself.
Step 2. Add notes
Essentially, a note consists of three properties: a 'title', a 'body', and a 'color'. These values
will be provided by the user. Each note will also include two additional properties: a unique 'id',
which identifies the note in the MongoDB collection, and an 'updated' property, which stores the
time that the note was last modified.
It's easy enough to build a form to match these properties. Here's what it looks like:
5. ibm.com/developerWorks/ developerWorks®
Build a notepad application with PHP, MongoDB, and IBM
Bluemix
Page 5 of 10
<form method="post" action="<?php echo $this->data['baseUri']; ?>/save">
<input name="id" type="hidden" value="<?php echo $this->data['note']['_id']; ?>" />
<div class="form-group">
<label for="title">Title</label>
<input type="title" class="form-control" id="title" name="title" placeholder="Title" value="<?php
echo htmlspecialchars($this->data['note']['title']); ?>">
</div>
<div class="form-group">
<label for="color">Color</label>
<input type="color" class="form-control" id="color" name="color" placeholder="Color" value="<?php
echo$this->data['note']['color']; ?>">
</div>
<div class="form-group">
<label for="body">Content</label>
<textarea name="body" id="body" class="form-control" rows="3"><?php echo htmlspecialchars($this-
>data['note']['body']); ?></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Save</button>
</div>
</form>
Notice that the form uses the new HTML5 'color' input type, which automatically produces a
color palette or color slider, allowing the user to select from a range of colors for each note. The
selected color is returned as a hexadecimal value.
To reduce duplication, it makes sense to reuse this form for editing existing notes. That's why the
form includes a hidden 'id' field, which will remain empty for new notes. The system can use the
presence or absence of this identifier to determine whether to create a new note in the database or
to update an existing one.
Here's the code fragment that initializes the database connection, using information sourced from
the <$APP_ROOT>/config.php file:
<?php
// attach configuration to application
$app->config = $config;
// extract database name from URI
// initialize PHP Mongo client
$dbn = substr(parse_url($app->config['db_uri'], PHP_URL_PATH), 1);
$mongo = new MongoClient($app->config['db_uri'], array("connectTimeoutMS" => 30000));
$db = $mongo->selectDb($dbn);
Once the form is submitted to the /save endpoint, the form processor must first validate and
sanitize the POST input, and then save it to the database. Here's what the callback function for
that process looks like:
6. developerWorks® ibm.com/developerWorks/
Build a notepad application with PHP, MongoDB, and IBM
Bluemix
Page 6 of 10
<?php
// handler to process form input
// save note content to database
$app->post('/save', function () use ($app, $db) {
$collection = $db->notes;
$id = trim(strip_tags($app->request->post('id')));
$note = new stdClass;
$note->title = trim(strip_tags($app->request->post('title')));
$note->body = trim(strip_tags($app->request->post('body')));
$note->color = trim(strip_tags($app->request->post('color')));
$note->updated = time();
if (!empty($id)) {
$note->_id = new MongoId($id);
}
$collection->save($note);
$app->redirect($app->urlFor('index'));
The code above sanitizes the POST input and sets the value of the 'updated' property to the
current time. Depending on whether the POST input contains an identifier, it either creates a new
MongoDB document for the note or uses the identifier to update an existing document with the
revised content.
Here's an example of what adding a new note looks like:
Step 3. List and search notes
Being able to add and update notes is just part of the picture; you also need to be able to list and
search for notes. Listing them is trivial: Simply update the callback for the /index route to retrieve
all the documents in the collection using the MongoDB client's find() method and hand them to
the view, sorted with the most recently updated first.
7. ibm.com/developerWorks/ developerWorks®
Build a notepad application with PHP, MongoDB, and IBM
Bluemix
Page 7 of 10
<?php
// handler to list available notes in database
$app->get('/index', function () use ($app, $db) {
$collection = $db->notes;
$notes = $collection->find()->sort(array('updated' => -1));
$app->render('index.tpl.php', array('notes' => $notes));
})->name('index');
Here's an example of what the output looks like:
If you have a large number of notes, listing them all isn't very practical. Ideally, you also want a
way to search note content for one or more keywords, so that you can quickly find the information
you're looking for.
1. The first step is to update the listing template with an additional search field, as shown below:
<div class="panel panel-default">
<form method="get" action="<?php echo $this->data['baseUri']; ?>/index">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="Search for...">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">Go!</button>
</span>
</div>
</form>
</div>
2. When a user enters a search term into the field, it's necessary to modify the generic "find
all documents" handler and retrieve only those documents where the 'title' or 'body'
properties contain a match to the search term. Here's the revised code:
<?php
// handler to list available notes in database
// if query string included
// filter results to match query string
$app->get('/index', function () use ($app, $db) {
$collection = $db->notes;
$q = trim(strip_tags($app->request->get('q')));
$where = array();
if (!empty($q)) {
$where = array(
'$or' =>
8. developerWorks® ibm.com/developerWorks/
Build a notepad application with PHP, MongoDB, and IBM
Bluemix
Page 8 of 10
array(
array(
'title' => array('$regex' => new MongoRegex("/$q/i"))),
array(
'body' => array('$regex' => new MongoRegex("/$q/i")))
)
);
}
$notes = $collection->find($where)->sort(array('updated' => -1));
$app->render('index.tpl.php', array('notes' => $notes));
})->name('index');
As the code above illustrates, when requests to the /index route include a query string, the
handler will generate an additional condition that returns only notes containing the search
term (expressed as a PHP MongoRegex object) in their title or body. This additional condition
is expressed in the $where variable, which is passed to the find() method as an additional
argument. The resulting data is transferred to the view and presented as before.
Here's an example of it in action:
Step 4. View and delete notes
You'll notice, from the previous image, that each note in the list includes a View button. This button
is hyperlinked to the /view route and includes the document ID for the corresponding note as a
request parameter. The /view callback handler merely needs to retrieve the specified note from
the database using the MongoDB client's findOne() method and display it, as shown in the code
below:
<?php
// handler to display specified note
$app->get('/view/:id', function ($id) use ($app, $db) {
$collection = $db->notes;
$note = $collection->findOne(array('_id' => new MongoId($id)));
$app->render('view.tpl.php', array('note' => $note));
});
Here's an example of what the output looks like:
9. ibm.com/developerWorks/ developerWorks®
Build a notepad application with PHP, MongoDB, and IBM
Bluemix
Page 9 of 10
Similarly, the /delete handler receives a document ID as a request parameter and uses the
MongoDB client's remove() method to delete the corresponding note from the database.
<?php
// handler to delete specified note
$app->get('/delete/:id', function ($id) use ($app, $db) {
$collection = $db->notes;
$collection->remove(array('_id' => new MongoId($id)));
$app->redirect($app->urlFor('index'));
});
Step 5. Deploy to Bluemix
1. At this point, the application is complete and can be deployed to Bluemix. First, update
the application configuration file and modify the database credentials so that they point to
your remote MongoDB database deployment. Then, create the application manifest file,
remembering to use a unique host and application name by appending a random string to it
(such as your initials).
---
applications:
- name: notes-[initials]
memory: 256M
instances: 1
host: notes-[initials]
buildpack: https://github.com/cloudfoundry/php-buildpack.git
stack: cflinuxfs2
2. The Cloud Foundry PHP buildpack doesn't include the PHP MongoDB extension by default,
so you must configure the buildpack to enable this extension during deployment. Create a <
$APP_ROOT>/.bp-config/options.json file with the following content:
{
"WEB_SERVER": "httpd",
"PHP_EXTENSIONS": ["bz2", "zlib", "curl", "mcrypt", "mongo"]
}
3. You can now go ahead and push the application to Bluemix.
shell> cf api https://api.ng.bluemix.net
shell> cf login
shell> cf push
4. You can start using the application by browsing to the host specified in the application
manifest (for example, http://notes-<initials>.mybluemix.net). If you see a blank page or other
errors, see "Debugging PHP Errors on IBM Bluemix" to find out where things are going wrong.