Skip to content
Permalink
Browse files

Week 3

  • Loading branch information...
susanBuck committed Feb 12, 2019
1 parent 9fac1ba commit 1659e65bc5063e84e23d0ebd5b0206e233d6fdeb
Showing with 930 additions and 0 deletions.
  1. +146 −0 misc/code-style.md
  2. BIN misc/dwa-phpstorm-settings.jar
  3. +55 −0 misc/interface.md
  4. +99 −0 misc/phpstorm.md
  5. +121 −0 php/cookies-and-sessions.md
  6. +93 −0 php/form-security.md
  7. +170 −0 php/forms.md
  8. +122 −0 php/loops.md
  9. +124 −0 php/syntactic-sugar.md
@@ -0,0 +1,146 @@
>> “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler, Refactoring: Improving the Design of Existing Code.

# Code style
It's common for development teams to have a coding style guide— a set of rules for how code should be written, which covers details like:

+ Case conventions - e.g., when/where to use lowerCamelCase, snake_case, UpperCamelCase, etc.
+ Structural conventions - e.g., whether to use spaces or tabs, where to place braces, what's the maximum length a line of code should be, etc.
+ Etc...

The purpose of a style guide is to keep work consistent amongst a group of developers. Even if you're working independently, abiding by a style guide will help produce more consistent code that's less prone to errors.

As an example, this is the [Ruby style guide that the team at Github.com uses](https://github.com/github/rubocop-github/blob/master/STYLEGUIDE.md).

On a more macro level, sometimes entire languages have dedicated style guides, such as the case with [Python's PEP 8 style guide](https://www.python.org/dev/peps/pep-0008/).

PHP has two style guides maintained by the [PHP Framework Interop Group (FIG)](http://www.php-fig.org):

+ [PSR-1 Basic Coding Standard](http://www.php-fig.org/psr/psr-1)
+ [PSR-2 Coding Style Guide](http://www.php-fig.org/psr/psr-2/)

When a language has an official style guide, it's not required that it be implemented 100%, and teams may decide to go off course with their own variations. The emphasis on style is not about which style guide you're following, simply that you are following *some* style guide and are aiming to be consistent and thoughtful in regards to code design.

**In this course, we will follow the PSR-1/PSR-2 guidelines in our PHP code files**

You can diverge from these guidelines, but you will be required to outline your divergences in your project's README.md file, and the divergences must be reasonable.

PhpStorm will *mostly* keep you in line with the guidelines, so use it to reformat your code often, and pay attention to warnings/notes it shows you.


## Example
Consider the following code example which is problematic in several ways:

```php
<?php
function getCelsius($temperature = NULL,$includeUnit = TRUE) {
# $x = ($temprature * 1.8 + 32 # f -> c
$x = ($temprature - 32) / 1.8
if ($includeUnit == TRUE) {
return $x .= ' C';
}
else{
return $x;
}
}
?>
```

Things PhpStorm will clean-up for you when you *Reformat Code*:
+ Constants, booleans, and null values should be lowercase.
+ Comma separated lists (e.g. the parameter list) should have a space after each comma.
+ Inconsistent spacing of braces after the `if` and `else`.
+ Function/method opening brace should be on its own line.
+ Unnecessary closing PHP tag.
+ Extra spacing between lines.
+ Incorrect indentation&mdash; the first `return` statement is a child of the `if` construct and thus it should be indented.

Things PhpStorm will alert you about:
+ There's a typo in the variable name (`$temprature` should be `$temperature`).
+ Missing semi-colon at the end of the line setting variable `$x`.
+ Unnecessary closing PHP tag

General problems that PhpStorm can't catch but you should be aware of:
+ The variable name `$x` is generic and in a larger context it could be confusing. A better name would be `$result`.
+ There's a commented-out line of code that's not being used, and no context is provided as to why it's still there. Lines like this should be cleaned up when finalizing a project. Exceptions are made if you comment that you're leaving the old code in for learning purposes.
+ The structure/use of the if/else construct and return statement could be optimized.

Here's that same example, cleaned up and optimized:
```php
<?php
function getCelsius($temperature = null, $includeUnit = true)
{
$result = ($temperature - 32) / 1.8;
if ($includeUnit) {
$result .= ' C';
}
return $result;
}
```



## Comments
>> "Good comments don't repeat the code or explain it. They clarify its intent. Comments should explain, at a higher level of abstraction than the code, what you're trying to do." -Steve McConnell
The PSR guidelines offer no rules on PHP commenting style, so any of the following PHP commenting styles are acceptable.

Multi-line block comment:
```php
/*
This is a
multi-line
comment in PHP
*/
```

Single line inline comments:
```php
# This is a single line in comment using a hash sign
// This is also a single line comment using two forward slashes, or "C++ style"
```



## Other, non-PHP code
There are no specific style guides I ask you adhere to when it comes to JavaScript, CSS, or HTML in your work.

However, just like PHP, it's expected that this code is consistent and neat for maximum legibility, __following the best practices and requirements for the respective language__.

That being said, here are some common issues I see in student's HTML code that you should avoid:

+ While the contents of most block elements should be indented appropriately, the contents of the `head` and `body` element should not be indented.
+ CSS and JS should always be linked externally, not applied inline or via embedded code.
+ Always use the most appropriate HTML element for the job
+ E.g. Don't use a `<h1>` tag just to make text big
+ E.g. Don't put the site's navigation links in a `<div>`, put them in a `<nav>`
+ Related: [Avoid div as much as possible](https://github.com/hail2u/html-best-practices#avoid-div-element-as-much-as-possible)
+ Likewise: [Avoid span as much as possible](https://github.com/hail2u/html-best-practices#avoid-span-element-as-much-as-possible)
+ [Don't mix quotation marks](https://github.com/hail2u/html-best-practices#dont-mix-quotation-marks)
+ [Write one list item per line](https://github.com/hail2u/html-best-practices#write-one-list-item-per-line)
+ [Use clear link text](https://github.com/hail2u/html-best-practices#clear-link-text)
+ [Don't use br element for presentational purpose](https://github.com/hail2u/html-best-practices#dont-use-br-element-only-for-presentational-purpose)
+ [Don't use placeholder attribute for labeling](https://github.com/hail2u/html-best-practices#dont-use-placeholder-attribute-for-labeling)
+ [Don't mix character cases](https://github.com/hail2u/html-best-practices#dont-mix-character-cases)

## Validating HTML
During development and before submission, run any/all pages of your project via the [w3 validator](https://validator.w3.org) to identify and fix any errors or warnings. (If you disagree with any of the warnings the validator is showing, email me ahead of time so we can confer on whether ignoring the warning is acceptable).

## PHP Code in display files
You may diverge PSR-1/PSR-2 guidelines in display files (.html, .blade.php) that incorporate PHP if it's for the purposes of writing more legible display code.





Binary file not shown.
@@ -0,0 +1,55 @@
# Interface
This is not a design course so your projects do not have to be works of art, but with a little bit of attention we can create clear and professional-looking interfaces.

Specifically, each project should abide by the following guidelines.

## Content
1. While your sub-domain and repository name may include terms like *P2* or *Project 2*, the application itself should be presented with a thoughtful and fitting title.
2. Every page should have a consistent header that features this title prominently at the top of the page. The title can be presented as text, or in the form of an image if presented as some stylized logo.
3. If your app has multiple pages, each page should have the same header and it should always link back to the homepage.
4. The homepage should have a welcome/introduction to the application explaining its purpose. Design your app as it were for an outside audience. If I were to pull someone off the street and ask them to interact with your site, it should make sense to them what the purpose of the site is and how to use it.

## Presentation
1. Copy/text should use proper English and be void of typos.
2. There should be a consistent and logical ordering in the size/presentation of headers.
3. Layout should look presentable on laptop/desktop resolution (responsive design is welcome, but not required).
4. Spacing and alignment should be used consistently and with intention.
5. Any graphics/images should be of good quality— there should be no pixelated, blurry, distorted, or otherwise low quality images.

## Usability
1. All links should be distinguished from regular text in some clear way (underlined, a different font color, etc.)
2. In most cases, button values should be changed from the default (i.e. *Submit*) to reinforce the action being taken (e.g. *Save changes*, *Place order*)
3. Any form inputs that are required should be labeled as such; exceptions are made for small forms where all inputs are implicitly required (e.g. a log in form)
4. Any form inputs that have non-obvious requirements should be labeled as such. For example, if a password must be at least 6 characters long, let the user know this in the form interface. Do not wait until the user has submitted the form to let them know about the requirement via your validation reporting.
5. Always provide feedback&mdash; your interface should speak to your user, letting them know when their actions are right, wrong, or misunderstood.
6. Feedback/results should stand out from the content of the rest of the page so they don't go unnoticed. Bold text, borders, varying background colors can help with this.
7. By convention error messages should be some variation of red (either in the text itself, or the background of the text). Green is a common color used for success/result messages.
7. Feedback/results should also be placed in a logical location; e.g. if a user submits a form and is immediately presented with the results, it's common for those results to be located somewhere near the button they pressed to submit the form. The user should not have to go hunting for results.

## Accessibility
1. The interface should be clearly legible&mdash; avoid...
+ Excessively small or large font sizes.
+ Low contrast color combinations (e.g. yellow on white).
+ Garish color combinations (e.g. bright green background, red text).


## Example
<img src='https://s3.amazonaws.com/dwa15.com/bad-vs-good-interface@2x.png' style='max-width:1044px;' alt=''>

### Issues
* Bad application title
* Bad hierarchy - (*Details* should not be more prominent than page heading)
* Lacks clear context/instructions
* Alignment is inconsistent and slightly off-center, both with the main sections of content (the results and form) and also within the form (labels and input)
* Results
+ unexpected location (top of page, not end of form below submit)
+ do not stand out from the rest of the content on the page and are easily missed
+ Unnecessary breaking of password text, which would make it hard to copy
+ Not enough distinction between label (*Your password*) and the password itself
* Form
* Required field and field restrictions (for number of words) not indicated.
* Unnecessary abbreviation (*Num word* should be *Number of words* or *How many words*)
* Number of words field unnecessarily long and inconsistent with the kind of data expected
* No styling distinction between primary and secondary form labels
* *Option* is labeling two inputs, so it should be plural
* Submit button value ("Submit") does not reinforce action of the button
@@ -0,0 +1,99 @@
# PhpStorm

PhpStorm is an IDE (Integrated Development Environment), which is a **super-powered code editor** packed with tools intended to make your development process easier. PhpStorm is most focused on PHP, but also has fantastic support for other languages (HTML, CSS, JS, Markdown, etc.).

+ [PhpStorm](https://www.jetbrains.com/phpstorm)
+ [Apply for a free education license](https://www.jetbrains.com/student)
+ [Help](https://www.jetbrains.com/help/phpstorm/)
+ [Full feature list](https://www.jetbrains.com/phpstorm/features)

An IDE is programmed to understand the code you're writing and assist you along the way with things like **code completion**, **on-the-fly error prevention**, **code clean-up and refactoring tools**, as well as **sophisticated tools for navigating through the structure of your code**.

Alternatives to IDEs include code editors such as [Sublime](https://www.sublimetext.com/3) or [Atom](https://atom.io).

Programs like Sublime text *can* be powerful, especially when you install plugins, but PhpStorm is powerful &ldquo;out of the box&rdquo; and it would take a lot of plugins to match the features in PhpStorm. Furthermore, even if you loaded Sublime with tons of plugins to get all the features you needed, the software would start to become bloated and you're not guaranteed all the various plugins are working seamlessly together.

The downside to IDEs is they're more complex and can be overwhelming at first with a steeper learning curve. Fortunately, though, PhpStorm is highly customizable so you can scale down all the features you're exposed to at first, and slowly bring the ones you need back into action as needed.

With all this being said though, having a basic editor like Sublime on hand can be useful for occasional quick edits to miscellaneous files when you're not in the middle of a set project.


## Simplify
If you're new to PhpStorm, I suggest importing my settings which will greatly simplify your interface and provide for a consistent experience with what you see in lecture videos.

As you become more comfortable with the program, you can branch out and customize the program to your liking.

1. Download [dwa-phpstorm-settings.jar](https://github.com/susanBuck/dwa15-spring2018/raw/master/misc/dwa-phpstorm-settings.jar)
2. *File* > *Import Settings* - select the `dwa-php-storm-settings.jar` file you just downloaded.

My settings include everything *except* keymaps, as this varies between Mac/Windows. More on customizing your keymaps in a moment.


## Projects
PhpStorm is centered around projects.

As an example, we'll create a new project out of our *hello-world* app from Week 2.

+ *File* > *Open* - find and select the *hello-world* directory.

*hello-world* is now loaded and initialized as a PhpStorm project.

Next time you close and re-open PhpStorm it will give you the option to re-open this project.

Optionally, you can always re-open a project by going to *File* > *Open* and re-selecting the appropriate directory.

### Project specific config
If you do a `git status` in your *hello-world* directory, you'll see a new folder called `.idea` which holds all the relevant PhpStorm settings for this project.

You probably don't want to track this directory in git, so in the root of your project, you want to edit/add a file called `.gitignore` and add the line `.idea` so it will ignore this directory.


## Tour of the interface
+ Top: Menus and toolbars
+ Left: Tool windows (project, navigation, favorites, etc.)
+ Right: Editor
+ Bottom: Status bar


## Customizing
Get into preferences:
+ Mac: *PhpStorm* > *Preferences*
+ Win: *File* > *Settings*

Skim through the settings to get a sense of what can be customized.

Note there's a search bar to find the setting you're looking for.

Customize what you see/don't see in the interface:
*Appearance & Behavior* > *Menus & Toolbars*


## Keymaps
Search by the command, or the existing keymap.

The following are the keyboard shortcuts I use most frequently. You should customize these as you see fit and get comfortable using them, especially *Reformat Code*

Most important:
+ `Cmd + A`: *Select all*
+ `Cmd + L`: *Reformat Code*
+ `Shift + Shift`: *Search Everywhere*

Others:
+ `Cmd + K`: *Hide All Tool Windows*
+ `Cmd + W`: *Close tab*


## Tools we're not using
+ Databases
+ Terminal
+ Version Control
+ Debugging



## Whitespace/Indentation
>> Code MUST use 4 spaces for indenting, not tabs. -[PSR-2 Coding Style Guide](https://www.php-fig.org/psr/psr-2/)
<img src='https://s3.amazonaws.com/dwa15.com/php-show-whitespaces-in-phpstorm.png' style='max-width:521px;' alt='PhpStorm settings for white space'>

<img src='https://s3.amazonaws.com/dwa15.com/php-phpstorm-indent-settings.png' style='max-width:521px;' alt=''>
Oops, something went wrong.

0 comments on commit 1659e65

Please sign in to comment.
You can’t perform that action at this time.