Development Workflow
Daily Development Workflow
Section titled “Daily Development Workflow”1. Start Your Day
Section titled “1. Start Your Day”# Navigate to projectcd ~/Desktop/mmp/mmp-webapp
# Pull latest changesmake pull
# Check for coworker's changesmake diff
# Start MySQL if neededmake db-start
# Start PHP dev servermake serverYour local app is now running at http://localhost:8000
2. Make Changes
Section titled “2. Make Changes”Edit files in your IDE/editor:
- PHP files for backend logic
- JavaScript files in
assets/js/ - CSS files in
assets/css/ - HTML in PHP templates
3. Test Locally
Section titled “3. Test Locally”# Access your local siteopen http://localhost:8000
# Test specific pagesopen http://localhost:8000/app-dashboard.phpopen http://localhost:8000/app-crm-full.php4. Commit Changes
Section titled “4. Commit Changes”# Check what changedgit status
# Stage changesgit add .
# Commit with descriptive messagegit commit -m "Fix: Resolve authentication redirect loop in app-auth.php"
# Push to GitHubgit push origin main5. Deploy
Section titled “5. Deploy”# Deploy to productionmake deploy
# Verify deploymentmake statusDevelopment Best Practices
Section titled “Development Best Practices”Environment Detection
Section titled “Environment Detection”The app auto-detects environment based on hostname:
// In config.phpif ($_SERVER['HTTP_HOST'] === 'localhost' || strpos($_SERVER['HTTP_HOST'], 'localhost:') === 0) { // Local development $host = 'localhost'; $db = 'mmp_app'; $user = 'root'; $pass = '';} else { // Production $host = 'my-marketing-pro.cluster-c3mws4moov6r.us-east-2.rds.amazonaws.com'; $db = 'mmp_app'; $user = 'admin'; $pass = 'J6Jq4i358ht)49';}Testing Changes
Section titled “Testing Changes”Always test locally before deploying:
- Functionality: Does it work as expected?
- Error handling: Check PHP warnings/errors
- Database: Verify queries work
- JavaScript: Check browser console
- Responsive: Test on different screen sizes
Database Changes
Section titled “Database Changes”If you modify database structure:
# Export schema from production (if needed)make db-export
# Or manually create migration scriptmysql -u root mmp_app < migrations/add_new_field.sqlRemember: Schema changes affect production!
File Changes
Section titled “File Changes”Before moving or renaming files:
# Search for referencesgrep -r "old-filename.php" .
# Check JavaScriptgrep -r "old-filename.php" assets/js/
# Check AJAX callsgrep -r "url.*old-filename" assets/js/Code Style Guidelines
Section titled “Code Style Guidelines”// Use descriptive variable names$userEmail = $row['email']; // Good$e = $row['email']; // Bad
// Always check for undefined array keys$redirect = $_GET['redirect'] ?? '';
// Use prepared statements for security$stmt = $db->prepare("SELECT * FROM app_users WHERE email = ?");$stmt->bind_param("s", $email);$stmt->execute();JavaScript
Section titled “JavaScript”// Use const/let, not varconst userId = document.getElementById('user-id').value;
// Use async/await for AJAXasync function fetchContacts() { const response = await fetch('/ajax/get-contacts.php'); const data = await response.json(); return data;}
// Handle errorstry { const contacts = await fetchContacts();} catch (error) { console.error('Error fetching contacts:', error);}-- Use clear table aliasesSELECT u.id, u.email, c.name as company_nameFROM app_users uLEFT JOIN app_contacts c ON u.id = c.user_id;
-- Add indexes for performanceCREATE INDEX idx_user_email ON app_users(email);Debugging
Section titled “Debugging”PHP Errors
Section titled “PHP Errors”Enable error reporting locally:
// Add to top of file temporarilyerror_reporting(E_ALL);ini_set('display_errors', 1);Check PHP logs:
# On serverssh mymarketingprotail -f /var/log/php/error.logDatabase Queries
Section titled “Database Queries”Test queries in MySQL:
# Connect locallymysql -u root mmp_app
# Run querySELECT * FROM app_users WHERE email = 'test@example.com';
# Explain query for performanceEXPLAIN SELECT * FROM app_users WHERE email = 'test@example.com';AJAX Debugging
Section titled “AJAX Debugging”Check browser console:
// Add console logsconsole.log('Request data:', requestData);
// Log responsesfetch('/ajax/endpoint.php') .then(response => response.json()) .then(data => console.log('Response:', data));Check network tab:
- Open DevTools (F12)
- Go to Network tab
- Make request
- Inspect request/response
Common Tasks
Section titled “Common Tasks”Adding a New Page
Section titled “Adding a New Page”- Create PHP file in root:
app-new-feature.php - Include necessary headers:
<?phpsession_start();require_once 'config.php';require_once 'includes/auth.php';?><!DOCTYPE html><html><head> <title>New Feature</title></head><body> <!-- Your content --></body></html>- Add to navigation if needed
- Test locally
- Commit and deploy
Adding an AJAX Endpoint
Section titled “Adding an AJAX Endpoint”- Create file in
ajax/directory:ajax/new-endpoint.php - Handle request:
<?phpsession_start();require_once '../config.php';
header('Content-Type: application/json');
// Validate sessionif (!isset($_SESSION['user_id'])) { echo json_encode(['error' => 'Unauthorized']); exit;}
// Process request$data = json_decode(file_get_contents('php://input'), true);
// Query database$stmt = $db->prepare("SELECT * FROM table WHERE id = ?");$stmt->bind_param("i", $data['id']);$stmt->execute();$result = $stmt->get_result();
// Return responseecho json_encode([ 'success' => true, 'data' => $result->fetch_assoc()]);- Call from JavaScript:
fetch('/ajax/new-endpoint.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: 123 })}).then(response => response.json()).then(data => console.log(data));Adding a Database Table
Section titled “Adding a Database Table”- Create migration script:
-- migrations/add_new_table.sqlCREATE TABLE IF NOT EXISTS app_new_table ( id INT PRIMARY KEY AUTO_INCREMENT, user_id INT NOT NULL, name VARCHAR(255), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES app_users(id));- Run locally:
mysql -u root mmp_app < migrations/add_new_table.sql- Run on production:
ssh mymarketingprocd /var/www/sftp/appmysql -h [rds-host] -u admin -p mmp_app < migrations/add_new_table.sqlPerformance Tips
Section titled “Performance Tips”Query Optimization
Section titled “Query Optimization”-- Bad: Loads all fieldsSELECT * FROM app_contacts;
-- Good: Only needed fieldsSELECT id, email, name FROM app_contacts;
-- Use indexesCREATE INDEX idx_email ON app_contacts(email);
-- Use LIMIT for paginationSELECT * FROM app_contacts LIMIT 50 OFFSET 0;Caching
Section titled “Caching”// Cache database results$cacheKey = 'user_' . $userId;if (isset($_SESSION[$cacheKey])) { $user = $_SESSION[$cacheKey];} else { $user = getUserFromDatabase($userId); $_SESSION[$cacheKey] = $user;}Minimize Database Calls
Section titled “Minimize Database Calls”// Bad: N+1 query problemforeach ($users as $user) { $contacts = getContactsForUser($user['id']); // Query in loop!}
// Good: Single query with JOIN$sql = " SELECT u.*, c.* FROM app_users u LEFT JOIN app_contacts c ON u.id = c.user_id";Security Checklist
Section titled “Security Checklist”Before deploying:
- SQL injection: Use prepared statements
- XSS: Escape output with
htmlspecialchars() - CSRF: Validate tokens on forms
- Authentication: Check session on protected pages
- File uploads: Validate file types
- Sensitive data: Never commit credentials
- Error messages: Don’t expose system details
Deployment Checklist
Section titled “Deployment Checklist”Before deploying:
- Code tested locally
- No PHP warnings/errors
- Database migrations tested
- JavaScript console clean
- Commit message descriptive
- Coworker notified of deployment
- Backup plan ready
After deploying:
- Test on production
- Check error logs
- Verify database changes
- Monitor for issues
Useful Commands
Section titled “Useful Commands”Database
Section titled “Database”# Export production schemamake db-export
# Import to localmake db-import
# Full syncmake db-sync
# Start/stop MySQLmake db-startmake db-stop# Pull latestmake pull
# Check coworker changesmake diff
# View commitsmake log
# Deploymake deployServer
Section titled “Server”# Start PHP servermake server
# SSH into productionmake ssh
# Check production statusmake statusNext Steps
Section titled “Next Steps”- Git Workflow - Version control process
- Deployment - Deployment procedures
- Makefile Commands - Command reference