Building Your Startup: Using Routes for Schedule With Me

This tutorial is part of the Building Your Startup With PHP series on ThemeKeeper Tuts+. In this series, I’m guiding you through launching a startup from concept to reality using my Meeting Planner app as a real-life example. Every step along the way, I’ll release the Meeting Planner code as open-source examples you can learn from. I’ll also address startup-related business issues as they arise.

Building Your Startup: Using Routes for Schedule With Me

Building Your Startup: Using Routes for Schedule With Me
Recently, I asked if our startup series has inspired any of your own entrepreneurial ideas and got you writing code. If so, please share a bit with us in the comments.

Let’s Meet, Visit My Schedule With Me Page

For a long time since I began this project, I’ve wanted Meeting Planner and Simple Planner to have a publicly accessible page you can share with people to schedule a meeting with you. In other words, “Sure, let’s meet, just visit my schedule with me page at Meeting Planner, I’m Bernie Sanders (no space).”

In today’s tutorial, I’ll show you I’ve done it using Yii’s routing and some of the related issues that came up.

If you haven’t tried scheduling a meeting yet, you can see how it’s done in this video:

The Schedule With Me page would be something like the PayPal Pay Me page:

Building Your Startup: Using Routes for Schedule With Me

I do participate in the comment threads below, so tell me what you think! You can also reach me on Twitter @lookahead_io. I’m especially interested if you want new features or to suggest topics for future tutorials.

As a reminder, all of the code for Meeting Planner is written in the Yii2 Framework for PHP. If you’d like to learn more about Yii2, check out our parallel series Programming With Yii2.

Let’s get started.

Planning the Schedule With Me Page

Building Your Startup: Using Routes for Schedule With Me

Note: Bernie’s not actually a Meeting Planner user, as far as I know.

Every Meeting Planner user has a unique username, e.g. berniesanders, and I decided to use this for the schedule with me URL. There were a few challenges to this feature:

  1. Designing the page
  2. Working with Yii Routing to map a root path to each person
  3. Managing the signup, login, and return to schedule

Designing the Page

Inspired by the PayPal Pay Me page (above) and others like it, I wanted to keep things simple initially. I used a responsive grid with offsets and centering:

<div class="col-lg-8 col-lg-offset-2 
    col-xs-10 col-xs-offset-1
        col-md-8 col-md-offset-2">
    <div class="centered schedule-me">
  

Here’s the /frontend/views/meeting/scheduleme.php view for the page:

<div class="scheduleme-top">
<div class="row">
  <div class="col-lg-8 col-lg-offset-2 col-xs-10 col-xs-offset-1 col-md-8 col-md-offset-2">
    <div class="centered schedule-me">
    <?php
     if ($userprofile->avatar<>'') {
       echo '<img src="'.Yii::getAlias('@web').'/uploads/avatar/sqr_'.$userprofile->avatar.'" class="profile-image"/>';
     } else {
       echo cebegravatarGravatar::widget([
            'email' => $user->email,
            'options' => [
                'class'=>'profile-image',
                'alt' => $user->username,
            ],
            'size' => 128,
        ]);
     }
     ?>
     <h1><?= $displayName ?></h1>
     <p class="lead">
       <?php if (Yii::$app->user->isGuest) { ?>
       <?= Html::a(Yii::t('frontend','Schedule a meeting with me'),['site/signup'])?>
       <?php } else { ?>
         <?= Html::a(Yii::t('frontend','Schedule a meeting with me'),['meeting/create','with'=>$user->username])?>
        <?php } ?>
       <p>
   </div>
  </div>
</div>
</div>

The code displays the profile image the user uploaded in user settings or uses a general Gravatar.

Of course, I used /frontend/web/css/site.css to customize the margins, border, and background:

.scheduleme-top {
  margin-top:8%;
}

.schedule-me {
background-color:#f3f3f3;
min-width:500px;
padding:100px 25px 65px 25px;
border:1px solid #e0e0e0;
}

// responsive adjustments 
@media only screen
  and (min-device-width: 320px)
  and (max-device-width: 667px)
  and (-webkit-min-device-pixel-ratio: 2) {
  
  ...
  
  .schedule-me {
      min-width:75%;
      padding:60px 10px 40px 10px;
    }

Managing the Yii Routing Changes

The routing for how Yii handles incoming browser requests is handled in /frontend/config/main.php under components. If you’re not careful with configuring this, you can destroy your whole application as incoming requests fail out to error pages.

Here’s the earlier routing before schedule with me:

<?php
$config = parse_ini_file('/var/secure/mp.ini', true);

$params = array_merge(
  require(__DIR__ . '/../../common/config/params.php'),
  require(__DIR__ . '/../../common/config/params-local.php'),
  require(__DIR__ . '/params.php'),
  require(__DIR__ . '/params-local.php')
);
return [
'components' => [
...
'urlManager' => [
  'class' => 'yiiwebUrlManager',
  'enablePrettyUrl' => true,
  'showScriptName' => false,
  //'enableStrictParsing' => false,
  'rules' => [
    'place' => 'place',
    'place/yours' => 'place/yours',
    'place/create' => 'place/create',
    'place/create_geo' => 'place/create_geo',
    'place/create_place_google' => 'place/create_place_google',
    'place/view/<id:d+>' => 'place/view',
    'place/update/<id:d+>' => 'place/update',
    'place/<slug>' => 'place/slug',
    '<controller:w+>/<id:d+>' => '<controller>/view',
    '<controller:w+>/<action:w+>/<id:d+>' => '<controller>/<action>',
    'daemon/<action>' => 'daemon/<action>', // incl eight char action
    'site/<action>' => 'site/<action>', // incl eight char action
    'features' => 'site/features',
    'about' => 'site/about',
    'wp-login|wp-admin' => 'site/neverland',
    '<username>/<identity:[A-Za-z0-9_-]{8}>' => 'meeting/identity',
    // note - currently actions with 8 letters and no params will fail
    '<controller:w+>/<action:w+>' => '<controller>/<action>',
  ],

I’ve written a bit before about routes in How to Program With Yii2: Sluggable Behavior, part of our Yii programming series, and you can read more background in the Yii documentation.

In Building Your Startup: Meetings With Multiple Participants, I wrote two episodes about dynamic paths by username for unique meeting URLs as shown below:

'<username>/<identity:[A-Za-z0-9_-]{8}>' => 'meeting/identity',

This broke lots of two-item routes such as meeting/[meeting_id] until I moved up more dynamic mapping above it to take precedence:

'<controller:w+>/<id:d+>' => '<controller>/view',
'<controller:w+>/<action:w+>/<id:d+>' => '<controller>/<action>',

And any second item paths with characters needed to be statically defined because our identity strings for meetings are eight characters, e.g. features.

Routes such as features are fixed, which goes to controller sites and action features as shown above. Remaining features are mapped dynamically as in: '<controller:w+>/<action:w+>' => '<controller>/<action>',.

Trying to create a one-item dynamic variable route such as /[username], e.g. https://meetingplanner.io/berniesanders, broke lots of single-item routes such as https://meetingplanner.io/about and the reminders page https://meetingplanner.io/reminder.

So I had to begin statically defining many of them.

Here’s the final routing with new static routes for one-word paths:

'urlManager' => [
    'class' => 'yiiwebUrlManager',
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    //'enableStrictParsing' => false,
    'rules' => [
      'place' => 'place',
      'place/yours' => 'place/yours',
      'place/create' => 'place/create',
      'place/create_geo' => 'place/create_geo',
      'place/create_place_google' => 'place/create_place_google',
      'place/view/<id:d+>' => 'place/view',
      'place/update/<id:d+>' => 'place/update',
      'place/<slug>' => 'place/slug',
      '<controller:w+>/<id:d+>' => '<controller>/view',
      '<controller:w+>/<action:w+>/<id:d+>' => '<controller>/<action>',
      'daemon/<action>' => 'daemon/<action>', // incl eight char action
      'site/<action>' => 'site/<action>', // incl eight char action
      'features' => 'site/features',
      'about' => 'site/about',
      'wp-login|wp-admin' => 'site/neverland',
      '<username>/<identity:[A-Za-z0-9_-]{8}>' => 'meeting/identity',
      'meeting' => 'meeting',
      'friend' => 'friend',
      'reminder' => 'reminder',
      'user-contact' => 'user-contact',
      'user-profile' => 'user-profile',
      'user-setting' => 'user-setting',
      '<username>' => 'meeting/scheduleme',
      // note - currently actions with 8 letters and no params will fail
      '<controller:w+>/<action:w+>' => '<controller>/<action>',
    ],
],

And you can check out “Bernie’s page” and schedule a meeting with him here:

https://simpleplanner.io/berniesanders

Note: Meeting Planner and Simple Planner work interchangeably, and I run both sites to offer users multiple brands. Simple Planner is for social get-togethers, and Meeting Planner is for more business-related stuff.

Managing Signup and Login From the Schedule With Me Page

Most people who initially visit a schedule with me page won’t have an account with us. So they’ll be redirected when they click Schedule With Me to the signup or login page.

After they log in, we want to return them to the meeting creation page pre-loaded with the owner of the schedule with me page added as a participant. We use setReturnUrl to do this:

Yii::$app->user->setReturnUrl(['meeting/create/','with'=>$u->username]);

It updates the session (usually through a cookie) so that after a person signs up or logs in, they are returned to the target page.

Here’s the full /frontend/controllers/MeetingController.php actionScheduleme method:

public function actionScheduleme() {
  $username = Yii::$app->request->getPathInfo();
  $u = User::find()
    ->where(['username'=>$username])
    ->one();
  if (is_null($u)) {
    return $this->goHome();
  } elseif (!Yii::$app->user->isGuest) {
      if (Yii::$app->user->getId()==$u->id) {
        Yii::$app->getSession()->setFlash('info', Yii::t('frontend','Welcome to your public scheduling page.'));            
      }
  }
  $userprofile = frontendmodelsUserProfile::find()
    ->where(['user_id'=>$u->id])
    ->one();
  Yii::$app->user->setReturnUrl(['meeting/create/','with'=>$u->username]);
  return $this->render('scheduleme', [
    'user'=>$u,
    'displayName'=> MiscHelpers::getDisplayName($u->id,true),
    'userprofile' => $userprofile,
  ]);
}

Adding the Schedule Page Owner as a Participant

Here’s the /frontend/controllers/MeetingController.php actionCreate method:

public function actionCreate($with = '')
{
...
    if ($with<>'') {
      $u = User::find()
        ->where(['username'=>$with])
        ->one();
        if (!is_null($u)) {
          $with_id =$u->id;
        } else {
          Yii::$app->getSession()->setFlash('error', Yii::t('frontend','Sorry, we could not locate anyone by that name. Visit support if you need assistance.'));
          $with_id =0;
        }
    } else {
      $with_id =0;
    }
    // prevent creation of numerous empty meetings
    $meeting_id = Meeting::findEmptyMeeting(Yii::$app->user->getId(),$with_id);
    if ($meeting_id===false) {
    // otherwise, create a new meeting
      $model = new Meeting();
      $model->owner_id= Yii::$app->user->getId();
      $model->sequence_id = 0;
      $model->meeting_type = 0;
      $model->subject = Meeting::DEFAULT_SUBJECT;
      $model->save();
      $model->initializeMeetingSetting($model->id,$model->owner_id);
      $meeting_id = $model->id;
    }
    if ($with_id!=0) {
        Participant::add($meeting_id,$with_id,Yii::$app->user->getId());
    }
    $this->redirect(['view', 'id' => $meeting_id]);
}

It processes the user id of the schedule with me page owner as $with_id to add them as a participant. And it also checks first to make sure there isn’t already a meeting in place between these two people—to prevent duplicates:

public static function findEmptyMeeting($user_id,$with_id = 0) {
  // if meeting with someone see if it exists already
  if ($with_id!=0) {
  // check for meeting with one participant with with_id
  $meetings = Meeting::find()->where(['owner_id'=>$user_id,'status'=>Meeting::STATUS_PLANNING])->limit(7)->orderBy(['id' => SORT_DESC])->all();
    foreach ($meetings as $m) {
      if (!is_null($m) && (count($m->participants)==1 && $m->participants[0]->participant_id==$with_id)) {
        return $m->id;
      }
    }
  }
  // looks for empty meeting in last seven
  $meetings = Meeting::find()->where(['owner_id'=>$user_id,'status'=>Meeting::STATUS_PLANNING])->limit(7)->orderBy(['id' => SORT_DESC])->all();
  foreach ($meetings as $m) {
    if (!is_null($m) and ($m->subject==Meeting::DEFAULT_SUBJECT || $m->subject=='') and (count($m->participants)==0 && count($m->meetingPlaces)==0 && count($m->meetingTimes)==0)) {
      return $m->id;
    }
  }
  return false;
}

I originally added the feature to prevent users from creating new meetings when there was already another empty new meeting they’d created previously.

Looking Ahead

There will be some things about this page I’ll clean up in the future as I speak to real users and gather feedback. Perhaps I’ll automatically share the user’s most frequent days and times for meetings. And I’ll create a user setting to turn off your scheduling page in case you don’t want it.

In Closing

All the work I’ve done recently with Bootstrap to create a better responsive interface for Meeting Planner made it easier for me to quickly code the schedule with me page.

Making sure the new Yii routes worked and didn’t break anything on the site was the hardest part of this. I also went and checked all of my Ajax calls to make sure none of them were affected.

I hope today’s tutorial was useful to you in learning to customize site URLs for your user base and the basics of MVC routing.

Have your own thoughts? Ideas? Feedback? You can always reach me on Twitter @lookahead_io directly. Watch for upcoming tutorials here in the Building Your Startup With PHP series. Some cool features are on their way.

Again, if you haven’t tried out Meeting Planner or Simple Planner yet, go ahead and schedule your first meeting.

Related Links