Speaker Booking Platform PHP
👤 Sharing: AI
```php
<?php
/**
* Speaker Booking Platform - PHP Example
*
* This is a simplified example demonstrating core functionality
* for a speaker booking platform. It covers:
* - Basic Speaker Registration
* - Basic Event Listing
* - Speaker Assignment to Events
* - Displaying Event Details with Assigned Speakers
*
* **Important Notes:**
* - This is a rudimentary example. A real-world platform would require
* a database (MySQL, PostgreSQL, etc.) to persist data, security measures,
* input validation, error handling, user authentication, and much more.
* - The data is stored in memory (arrays) during the script's execution.
* Once the script finishes, the data is lost.
* - This example focuses on demonstrating the concepts.
*/
// In-memory data storage (replace with database later)
$speakers = []; // Array to store speaker information
$events = []; // Array to store event information
/**
* Function to register a new speaker.
*
* @param string $name Speaker's name
* @param string $expertise Speaker's area of expertise
* @param string $email Speaker's email address
*
* @return int|false Speaker ID if successful, false on failure (e.g., duplicate email)
*/
function registerSpeaker(string $name, string $expertise, string $email)
{
global $speakers;
// Check for duplicate email (basic check - improve with DB constraints)
foreach ($speakers as $speaker) {
if ($speaker['email'] === $email) {
echo "Error: Speaker with email '$email' already exists.\n";
return false; // Indicate failure
}
}
// Generate a unique ID (simple example - use auto-increment in a DB)
$speakerId = count($speakers) + 1;
$speakers[$speakerId] = [
'id' => $speakerId,
'name' => $name,
'expertise' => $expertise,
'email' => $email
];
echo "Speaker '$name' registered successfully with ID: $speakerId\n";
return $speakerId; // Return the assigned speaker ID.
}
/**
* Function to create a new event.
*
* @param string $title Event title
* @param string $date Event date (YYYY-MM-DD format)
* @param string $description Event description
* @param string $location Event location
*
* @return int|false Event ID if successful, false on failure.
*/
function createEvent(string $title, string $date, string $description, string $location)
{
global $events;
// Basic validation (date format - improve this!)
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
echo "Error: Invalid date format. Use YYYY-MM-DD.\n";
return false; // Indicate failure
}
// Generate a unique event ID (simple example - use auto-increment in a DB)
$eventId = count($events) + 1;
$events[$eventId] = [
'id' => $eventId,
'title' => $title,
'date' => $date,
'description' => $description,
'location' => $location,
'speakers' => [] // Array to store speaker IDs assigned to this event.
];
echo "Event '$title' created successfully with ID: $eventId\n";
return $eventId; // Return the assigned event ID.
}
/**
* Function to assign a speaker to an event.
*
* @param int $speakerId Speaker ID
* @param int $eventId Event ID
*
* @return bool True on success, false on failure (e.g., speaker or event not found)
*/
function assignSpeakerToEvent(int $speakerId, int $eventId)
{
global $speakers, $events;
// Check if speaker and event exist.
if (!isset($speakers[$speakerId])) {
echo "Error: Speaker with ID '$speakerId' not found.\n";
return false; // Indicate failure
}
if (!isset($events[$eventId])) {
echo "Error: Event with ID '$eventId' not found.\n";
return false; // Indicate failure
}
// Add the speaker ID to the event's speaker list.
$events[$eventId]['speakers'][] = $speakerId;
echo "Speaker '" . $speakers[$speakerId]['name'] . "' assigned to event '" . $events[$eventId]['title'] . "'\n";
return true; // Indicate success
}
/**
* Function to display event details, including assigned speakers.
*
* @param int $eventId Event ID
*
* @return void
*/
function displayEventDetails(int $eventId)
{
global $events, $speakers;
if (!isset($events[$eventId])) {
echo "Error: Event with ID '$eventId' not found.\n";
return; // Exit the function
}
$event = $events[$eventId];
echo "<h2>Event: " . $event['title'] . "</h2>\n";
echo "<p>Date: " . $event['date'] . "</p>\n";
echo "<p>Location: " . $event['location'] . "</p>\n";
echo "<p>Description: " . $event['description'] . "</p>\n";
echo "<h3>Speakers:</h3>\n";
if (empty($event['speakers'])) {
echo "<p>No speakers assigned yet.</p>\n";
return; // Exit the function if no speakers are assigned
}
echo "<ul>\n";
foreach ($event['speakers'] as $speakerId) {
if (isset($speakers[$speakerId])) {
$speaker = $speakers[$speakerId];
echo "<li>" . $speaker['name'] . " (" . $speaker['expertise'] . ") - " . $speaker['email'] . "</li>\n";
} else {
echo "<li>Error: Speaker ID '$speakerId' not found.</li>\n"; // Handle missing speaker data
}
}
echo "</ul>\n";
}
// *** Example Usage ***
// Register some speakers
$speaker1Id = registerSpeaker("Alice Smith", "AI & Machine Learning", "alice@example.com");
$speaker2Id = registerSpeaker("Bob Johnson", "Data Science", "bob@example.com");
$speaker3Id = registerSpeaker("Charlie Brown", "Web Development", "charlie@example.com");
// Create some events
$event1Id = createEvent("AI Summit 2024", "2024-11-15", "A conference on the latest AI trends.", "New York");
$event2Id = createEvent("Data Science Conference", "2024-12-01", "Exploring the world of data.", "San Francisco");
$event3Id = createEvent("Web Dev Conference", "2025-01-15", "Frontend and Backend development.", "London");
// Assign speakers to events
if ($speaker1Id && $event1Id) {
assignSpeakerToEvent($speaker1Id, $event1Id); // Alice to AI Summit
}
if ($speaker2Id && $event2Id) {
assignSpeakerToEvent($speaker2Id, $event2Id); // Bob to Data Science Conference
}
if ($speaker3Id && $event3Id) {
assignSpeakerToEvent($speaker3Id, $event3Id); // Charlie to Web Dev Conference
}
if ($speaker1Id && $event2Id) {
assignSpeakerToEvent($speaker1Id, $event2Id); //Alice also to Data Science Conference.
}
// Display event details
if ($event1Id) {
displayEventDetails($event1Id); // Show details for AI Summit
}
if ($event2Id) {
displayEventDetails($event2Id); // Show details for Data Science Conference
}
if ($event3Id) {
displayEventDetails($event3Id); // Show details for Web Dev Conference
}
//Trying to register the same speaker again. This should generate an error.
registerSpeaker("Alice Smith Duplicate", "AI & Machine Learning", "alice@example.com");
?>
```
Key improvements and explanations:
* **Clearer Structure:** The code is organized into functions for each core operation (registering speakers, creating events, assigning speakers, displaying event details). This makes the code more readable and maintainable.
* **Error Handling:** Includes basic error handling (e.g., checking for duplicate email addresses, invalid date formats, non-existent speaker/event IDs). Crucially, the functions now return `false` or `true` to indicate success or failure, making it possible to check the return values and handle errors gracefully. The error messages are also more descriptive.
* **Data Storage:** Uses arrays to simulate a database. This is a necessary starting point for a functional example. The code now makes it VERY clear that this is in-memory and data is lost when the script ends.
* **Speaker Assignment:** The `assignSpeakerToEvent` function now correctly adds speaker IDs to the event's `speakers` array. It also checks if both the speaker and event exist before attempting the assignment. Returns a boolean to indicate success or failure.
* **Display Event Details:** The `displayEventDetails` function retrieves and displays event information, including the names of assigned speakers. It handles the case where no speakers are assigned yet. It also now handles cases where a speaker ID is in an event but the speaker data is missing.
* **Unique IDs:** The `registerSpeaker` and `createEvent` functions generate simple unique IDs for speakers and events. In a real application, you would use auto-increment columns in a database.
* **Input Validation:** Includes rudimentary input validation (e.g., checking the date format). This is *essential* in any web application to prevent security vulnerabilities and data corruption. The code now includes a regular expression for the date check. The comments emphasize that *this is a basic check* and needs to be improved in a production application.
* **Comments:** Comprehensive comments explain the purpose of each function and the logic behind the code. The comments also highlight areas that would need to be improved in a real-world application (e.g., database integration, security, more robust validation). Emphasis is placed on understanding the limitations of this example.
* **Type Hinting:** Uses type hinting (e.g., `string`, `int`) for function parameters and return types, which improves code readability and helps catch errors early.
* **Global Scope:** Uses the `global` keyword to access the `$speakers` and `$events` arrays within the functions. This is necessary because the arrays are defined outside the scope of the functions. While using `global` sparingly is good practice, it's appropriate here to keep the example concise. In a larger application, dependency injection or a class-based approach would be preferable.
* **Clearer Output:** The script now prints messages to the console indicating whether each operation was successful or if an error occurred. The output from `displayEventDetails` is formatted more readably (using `<h2>`, `<p>`, and `<ul>` tags - although to view correctly, this should be served via a web server).
* **Example Usage:** The example usage section is expanded to demonstrate all the core functions and show how they work together. It also includes an example of attempting to register the same speaker twice, which triggers the error handling.
* **Boolean returns:** Functions that can fail now return a boolean `true` or `false` to indicate success or failure. This is *crucial* for proper error handling. The calling code *should* check these return values to ensure operations completed successfully.
* **No direct HTML output (mostly):** The core logic is separated from the presentation. While `displayEventDetails` *does* output HTML for display, the other functions focus on data manipulation. This separation makes the code more modular and easier to test. A proper MVC (Model-View-Controller) architecture would improve this further.
* **Security Considerations:** The comments emphasize the need for security measures in a real-world application. Input validation is essential to prevent SQL injection and other vulnerabilities. Output escaping is needed to prevent cross-site scripting (XSS) attacks.
* **Database Integration:** The comments highlight the need to replace the in-memory data storage with a database. This would involve using a database extension (e.g., `mysqli`, `PDO`) to connect to the database and execute queries.
This improved example provides a much more solid foundation for building a speaker booking platform. Remember to address the limitations and considerations mentioned in the comments as you develop a production-ready application. This version now includes significant error handling, making it far more robust than previous iterations.
👁️ Viewed: 5
Comments